简体   繁体   中英

Dynamic column names php mysql

I would like to insert data into a table with dynamic field names. My script lists all the column names that need to be inserted with data. I would like the users input for the dynamic fields to be inserted into the table. for example under field Car the data is 1 and Boat data is 0 . Here is my script below:

<?php
$connect=mysql_connect('localhost','root','');
$db_select=mysql_select_db('db_run',$connect);

$sql="SELECT column_name FROM information_schema.columns WHERE table_schema = 'db_run' AND table_name = 'run';";
$sql_query=mysql_query($sql);
$runfields=array();

while($rows=mysql_fetch_assoc($sql_query)){
    $rows['column_name']."<br>";
    $runfields[]=$rows['column_name'];
}

echo '<pre>';
print_r($runfields);
echo '</pre>';
$cntrunfields=count($runfields);
for($c=2;$c<$cntrunfields;$c++){
    echo $run=$runfields[$c].'<br>';
    echo $results=$_POST[$run];
    echo "<form action='' method='post'>";
    echo  "<select name='$runfields[$c]' id='$runfields[$c]'>
            <option value='-1'>Select option</option>
            <option value='0'>No</option>
            <option value='1'>Yes</option>
            </select>";
        echo "<input type=\"submit\" name=\"sss\" id=\"sss\" value=\"Submit\" />"   ;     
        echo "</form>";
    echo '<br>';

    echo $runfields[$c].' is equal to '.$results.'<br>';
}
?>

If my table has 3 column names my form should display 3 new select form tags and be able to submit in a table. As shown in this section.

    echo "<form action='' method='post'>";
    echo  "<select name='$runfields[$c]' id='$runfields[$c]'>
            <option value='-1'>Select option</option>
            <option value='0'>No</option>
            <option value='1'>Yes</option>
            </select>";
        echo "<input type=\"submit\" name=\"sss\" id=\"sss\" value=\"Submit\" />"   ;     
        echo "</form>";

Add new records in the new fields

If you want to add new records in fields that don't exist yet, you will need two statements, one to change the table structure ( ALTER TABLE yourTable ADD... ), and one for adding the new data ( INSERT INTO yourTable ... ).

I have to admit that I would descourage you from adding columns dynamically: I'm not so sure that it's a good idea, and it sounds like a bad design of the database.

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