Rhs
Rhs

Reputation: 3318

MySql/PHP Insert SET Last_Insert_ID()

I have the following PHP Code

$con = mysqli_connect($host, $user, $password, $database) or die ("Couldn't connect to database"); //assume these variables are declared

$sql = "INSERT INTO Users
       (
           FirstName
           ,MiddleName
           ,LastName
       )
       Values
       (
           'John'
           ,'A'
           ,'Smith'
       );

       SET @petID = LAST_INSERT_ID();

       INSERT INTO Pets
       (
           UserID
           ,Name
       )
       Values
       (
           @petID
           ,'myPet'
       );";

if(!mysqli_query($con, $sql))
{
    die('Error: ' . mysqli($con));
}

mysqli_close($con);

When I attempt to execute this code, this error happens:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @petID = LAST_INSERT_ID(); INSERT INTO Pets ( UserID ,Name ' at line 24

To test if there was an error with mySql syntax, I put the string in a file and ran it directly using: mysql -u root -p myDatabase < InsertSqlStatement.sql The statement executed without any problems.

What is wrong with my PHP Code?

Upvotes: 0

Views: 201

Answers (3)

ChunkyBaconPlz
ChunkyBaconPlz

Reputation: 580

MySQLi won't do multiple queries for security purposes; you want mysqli_multi_query:

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

Upvotes: 3

Sven
Sven

Reputation: 70923

You cannot execute more than one SQL query in a call to mysqli_query. If you want to execute multiple queries, either send them one by one or make use of mysqli_multi_query.

Upvotes: 2

Marc B
Marc B

Reputation: 360862

You cannot run multiple queries within a single query() call in PHP. This is a simplistic security mechanism against some forms of SQL injection attacks. This is built into mysql PHP drivers, and is not something you can bypass. It runs properly when you copy the query string and run it seperately, because the command line tools are NOT bound by the same restriction.

You'll have to run the queries separately:

$result = mysqli_query('INSERT ...');
$result = mysqli_query('SELECT @petID = ...');
$result = mysqli_query('INSERT ....');

Upvotes: 1

Related Questions