MYSQL用select插入值

时间:2018-10-20 14:01:34

标签: php sql

我正在尝试插入这样的值:

$sql = "INSERT INTO daily_food (number, weight, title, price) VALUES ('1', SELECT weight, title, price FROM food where title = '$add_food' LIMIT 1)";
mysqli_query($conn, $sql);

我有要选择的食物数据库。我也想插入该数字,但是代码无能为力。我是sql的新手,所以我不知道代码的外观。

1 个答案:

答案 0 :(得分:2)

只需使用insert . . . select,就不需要使用values

INSERT INTO daily_food (number, weight, title, price) 
    SELECT 1, weight, title, price
    FROM food 
    WHERE title = '$add_food'
    LIMIT 1;

我假设number实际上是一个数字,因此不需要引号。

此外,您应该将$add_food作为参数传递,如下所示:

INSERT INTO daily_food (number, weight, title, price) 
    SELECT 1, weight, title, price
    FROM food 
    WHERE title = ?
    LIMIT 1;