简体   繁体   English

动态列名称php mysql

[英]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 . 例如,在字段Car ,数据为1Boat数据为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. 如果我的表有3个列名,则我的表单应显示3个新的select表单标记,并能够在表中提交。 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 ... ). 如果要在尚不存在的字段中添加新记录,则需要两条语句,一条用于更改表结构( ALTER TABLE yourTable ADD... ),一条用于添加新数据( 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. 我必须承认,我不鼓励您动态添加列:我不确定这是一个好主意,而且听起来像是数据库的设计不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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