MySQL Inserts an update table as an array

Source: Internet
Author: User

In the project with Php+mysql, you need to insert data, but the database table field is very long, if you use the regular INSERT into table (c) VALUES (' DD '), it will be a long SQL statement, and accidentally, it is wrong.

So the general use of arrays to operate, a lot of frameworks have specialized features, such as thinkphp table mapping, available

$result $model->add ($post//

But the original how to do, the following is my summary, although seemingly cumbersome, but definitely more efficient than the original; The code is as follows:

<?PHP//a,b,c,d fields for the table, there are many fields in my actual project$data[' a '] =$_post[' A ']; $data[' B '] =$_post[' B ']; $data[' c '] =$_post[' C ']; $data[' d '] =$_post[' d ']; foreach($data  as $k=$v){       $k 1[] = "".$k.‘ '//use a field as an array;     $v 1[] = ' "'.$v.‘"‘;//The inserted value as an array;  }     $STRV.=implode(‘,‘,$v 1); $STRK.=implode(",",$k 1);Echo' <br> insert code below ';$sql= "INSERT INTO TB ($STRK) VALUES ($STRV)";Echo $sql;Echo' <br> below for update code ';Echo' <br> ';foreach($data  as $k=$v){       $str[] = "`".$k." ' = ' ".$v."‘";//use a field as an array;          } $strs=implode(‘,‘,$str);$sql= "Update TB Set$strswhere id=1 ";Echo $sql; ?> <form action= "" method= "Post" name= "ASP" >Box 1: <input type= "text" Name= "a" value= "1"/>Box 2: <input type= "text" name= "B" value= "2"/>Box 3: <input type= "text" Name= "C" value= "3"/>Box 4: <input type= "text" name= "D" value= "4"/> <input type= "Submit" Name= "Download" vaue= "Download"/> & Lt;/form>

Only the code that generated the MySQL statement is written here!

MySQL Inserts an update table as an array

Related Article

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.