0

I want to insert multiple tables in same query with table2 retrieve the id from table1

Here's my sql code

 $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);

It shown the syntax error. but I copied the output of $q to Run in SQL query at phpMyAdmin it worked. Could you anyone point me out where is my mistake?

    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
ajjumma
  • 103
  • 2
  • 3
  • 11

3 Answers3

2

I don't believe that you can run multiple statements with a single query call; you need to call mysqli_multi_query instead:

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

andrewsi
  • 10,807
  • 132
  • 35
  • 51
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].'"');
}
Man Programmer
  • 5,300
  • 2
  • 21
  • 21
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).

read C API Support for mysql

Arun Killu
  • 13,581
  • 5
  • 34
  • 61