简体   繁体   中英

How to insert dynamic value into mysql database

i have a form which content name,phone no ,address,personal info....etc

and i had given an option to user which fields he want to insert using a checkbox

the field which is has checked apper on other page eg: if he has seleted name and address

...then name and address appers....so how can i make my mysql database.....so if someone select all option in my form ....my mysql table should save all data...

so basically my question is how can i make my mysql database dynamically...so if user selets 2 option it can insert 2 values & if user select all option he can save all the values.....

First of all you have be clear is their any mandatory field in all your fields and i think it must be some mandatory otherwise what will happen is if user will just submit form it will insert blank row into database so be clear which field you want to make mandatory.

Then put all others in checkbox and make a database table with all the fields name with default value null.

and use a array to insert data into database each time in this way you dont have to write every time the fields name and their value

< form >
     < input type="text" name="detail['name']" value="" / >
     < input type="text" name="detail['age']" value="" / >
     < input type="text" name="detail['email']" value="" / >
     .
     .
     .
     .
   < / form >

what will you get on another end

 $detail = $_POST['detail'];

now all the values posted from form with their fields name are inside $detail.

No its your turn to make a query which will take key of $detail array as columns of table and value of $detail is value to be inserted in db like

 $field_string = '';
 $value_string = '';

 foreach($detail as $key => $val){

   $field_string = $key.",";
   $value_string = $value.",";       

 }
 $field_string = trim($field_string, ",");
 $value_string = trim($value_string, ",");

$query = "INSERT INTO table ($field_string) VALUES ($value_string) ";

That's all i hope this will help you

使用数据库中的所有字段创建表。将插入selected选项的字段值,对于其他字段,将插入null

您所能做的就是或者创建一个具有表所有列的数据库,或者只是在表中一次又一次地添加一列( if it does not exist但是即使您不存在,已经添加到数据库中的列也将存在。在其中添加数据,直到将其删除

first get all column number with following select statement (during the example i assume you have a class (as always i have) to read the data from DB)

select count(*) from cols where table_name='MyTableName'

if the number of row was same as answer of above query so you have to show

select * from MyTableName

if not :

i assume you save the data in $UserSelectedField

$userSelectedField=implode($UserSelectedField,',');
$sql="select $UserSelectedField from MyTableName ";

then you can show the answer of $sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM