简体   繁体   中英

create mysql query from a colum in a second table

I have a piece of code that should get the names of food items that are not ingredients from one table and then generate a query to create another table with columns matching the names of those items this is not generating a table:

function create_table(){
$query = "SELECT * FROM food";
$tablequery = "CREATE TABLE (id int(6) NOT NULL auto_increment,";
if($result=mysql_query($query)){
    while($row = mysql_fetch_array($result)){
        if($result['ingredient'] != 1){
            $tablequery = $tablequery.$result['name']."varchar(30) NOT NULL,";
        }
    }
    $tablequery = $tablequery."PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))";
}
mysql_query($tablequery);

}

I did call the function so that is not the problem and somehow it worked once but with just the id.

Try this:

while($row = mysql_fetch_assoc($result)){
    if($row['ingredient'] != 1){
        $tablequery = $tablequery.$row['name']."varchar(30) NOT NULL,";
    }
}

我认为您需要在代码中添加一行以删除表(如果该表已经存在):

 DROP TABLE IF EXISTS `<your table>`;

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