2014-01-22 99 views
0
$this->db->query("INSERT INTO products 
       (name, price, description, stock) 
       VALUES ('$name', '$price', '$description', '$stock')"); 

$this->db->query("INSERT INTO products (category) 
       SELECT id 
       FROM categories 
       WHERE category_name = '$category'"); 

這些查詢工作正常,如果單獨運行,但是如何將它們一起運行? 我正在嘗試將產品數據添加到表中,並且同時獲取類別ID並將其插入。運行兩個查詢,INSERT和INSERT INTO SELECT(php,mysql)

+0

使用交易。 – BaBL86

回答

1

在一般情況下,你可以在SELECT

INSERT INTO table1 (col1, col2, col3) 
    SELECT id, 'string1', 'string2' 
    FROM table2 
    WHERE cond1 = val4; 

指定硬編碼值,將增加的價值,如果idstring1string2table1

在你的情況應該是

INSERT INTO products (category, name, price, description, stock) 
       SELECT id, '$name', '$price', '$description', '$stock' 
       FROM categories 
       WHERE category_name = '$category'