0

我想在同一个查询中插入多个表,使用 table2 从 table1 检索 id

这是我的sql代码

 $q = "
    INSERT INTO Product (pName, pBrand, pCategory, pSize, pQuantity, pPrice, pDetail)
        VALUES('$name', '$brand', '$category', '$size', '$quantity', '$price', '$detail');
    INSERT INTO Image (iName, iExt, iSize, pID)
        VALUES('$img_name', '$img_ext', '$img_size', LAST_INSERT_ID());";

 $mysqli->query($q);

它显示了语法错误。但我将 $q 的输出复制到在 phpMyAdmin 的 SQL 查询中运行,它起作用了。你能指出我的错误在哪里吗?

    INSERT INTO Product (pName, pBrand, pCategory, pSize, pQuantity, pPrice, pDetail)
        VALUES(....); #1 row affected
    INSERT INTO Image (iName, iExt, iSize, pID)
        VALUES(....); #1 row affected
4

3 回答 3

2

我不相信您可以通过单个查询调用运行多个语句;你需要打电话mysqli_multi_query

http://php.net/manual/en/mysqli.multi-query.php

于 2012-09-29T04:52:11.940 回答
0
$q = "
    INSERT INTO Product (pName, pBrand, pCategory, pSize, pQuantity, pPrice, pDetail)
        VALUES('$name', '$brand', '$category', '$size', '$quantity', '$price', '$detail');
    INSERT INTO Image (iName, iExt, iSize, pID)
        VALUES('$img_name', '$img_ext', '$img_size', LAST_INSERT_ID());";
$arr=explode(";",$q)
for($i=0;isset($arr[$i]);$i++)//or use limit($arr) in place of isset
{

 $mysqli->query('"'.$arr[$i].'"');
}
于 2012-09-29T05:06:18.360 回答
0
    By default, mysql_query() and mysql_real_query() 
interpret their statement string argument 
as a single statement to be executed, and you process
 the result according to whether 
the statement produces a result set 
(a set of rows, as for SELECT) 
or an affected-rows count (as for INSERT, UPDATE, and so forth).

阅读 C API 对 mysql 的支持

于 2012-09-29T05:07:11.870 回答