0

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>";
4

1 回答 1

0

在新字段中添加新记录

如果要在尚不存在的字段中添加新记录,则需要两条语句,一条用于更改表结构(ALTER TABLE yourTable ADD...),一条用于添加新数据(INSERT INTO yourTable ...)。

我不得不承认我会劝阻您不要动态添加列:我不太确定这是一个好主意,而且这听起来像是一个糟糕的数据库设计。

于 2013-01-04T10:18:07.277 回答