PHP implementation _php Instance of SQL statement to execute with array

Source: Internet
Author: User

Will the

Encounter such a situation? Every time you get the data there is a difference between the data and the history version, but with the thinkphp AddAll () function, the existing data is deleted and rewritten. It's obviously not what we want. But write your own SQL every dozens of fields is also drunk. How to automate the generation of SQL gracefully and easily? So here's the way.

/** * [array_to_sql concatenation of required SQL according to array key and value] * @param [type] $array [key, array of value structures
   ] * @param string $type [SQL Type insert,update] * @param array $exclude [excluded fields] * @return [string] [return concatenation of SQL]
    */function Array_to_sql ($array, $type = ' Insert ', $exclude = Array ()) {$sql = '; if (count ($array) > 0) {foreach ($exclude as $exkey) {unset ($array [$exkey]);//Remove No key} if (
        ' Insert ' = = $type) {$keys = Array_keys ($array);
        $values = Array_values ($array);
        $col = Implode ("', '", $keys);
        $val = Implode ("', '", $values);
      $sql = "(' $col ') VALUES (' $val ')";
        }else if (' update ' = = $type) {$tempsql = ';
        $temparr = Array ();
          foreach ($array as $key => $value) {$tempsql = "' $key ' = ' $value '";
        $temparr [] = $tempsql;
      $sql = Implode (",", $temparr);
  } return $sql; }

Of course, there are many things to consider about this approach. Can be used, but not the best. Garden Ape Apes, do you have a better way? Please tell me!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.