ajjumma
ajjumma

Reputation: 103

MySQL: Trouble with LAST_INSERT_ID()

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

Upvotes: 0

Views: 194

Answers (3)

Arun Killu
Arun Killu

Reputation: 14263

    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

Upvotes: 0

Man Programmer
Man Programmer

Reputation: 5356

$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].'"');
}

Upvotes: 0

andrewsi
andrewsi

Reputation: 10732

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

Upvotes: 2

Related Questions