Php uses arrays to generate SQL statements to execute.

Source: Internet
Author: User

Php uses arrays to generate SQL statements to execute.

Will this happen? The data obtained each time is different from the previous version. However, the addAll () function of ThinkPHP deletes the existing data and writes it again. This is obviously not what we want. However, I am also drunk when I write SQL statements on dozens of fields each time. How can we achieve SQL Automatic Generation elegantly and easily? So we have the following method.

/*** [Array_to_ SQL Concatenates the array key and value into the required SQL] * @ param [type] $ array [key, value structure array] * @ param string $ type [SQL type insert, update] * @ param array $ exclude [excluded fields] * @ return [string] [return spliced SQL] */function array_to_ SQL ($ array, $ type = 'insert ', $ exclude = array () {$ SQL = ''; if (count ($ array)> 0) {foreach ($ exclude as $ exkey) {unset ($ array [$ exkey]); // remove unnecessary keys} 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, this method has many points to consider. Usable, but not the best. Do you have a better method for yuanshu? Please let me know!

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.