简体   繁体   English

MySql / PHP插入SET Last_Insert_ID()

[英]MySql/PHP Insert SET Last_Insert_ID()

I have the following PHP Code 我有以下PHP代码

$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. 为了测试mySql语法是否存在错误,我将字符串放入文件中,然后使用以下命令直接运行它: mysql -u root -p myDatabase < InsertSqlStatement.sql执行该语句没有任何问题。

What is wrong with my PHP Code? 我的PHP代码有什么问题?

MySQLi won't do multiple queries for security purposes; 为了安全起见,MySQLi不会执行多个查询。 you want mysqli_multi_query: 您想要mysqli_multi_query:

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

You cannot execute more than one SQL query in a call to mysqli_query . 在对mysqli_query的调用中,不能执行多个SQL查询。 If you want to execute multiple queries, either send them one by one or make use of mysqli_multi_query . 如果要执行多个查询,请一个接一个地发送它们,或使用mysqli_multi_query

You cannot run multiple queries within a single query() call in PHP. 您不能在PHP的单个query()调用中运行多个查询。 This is a simplistic security mechanism against some forms of SQL injection attacks. 这是一种针对某些形式的SQL注入攻击的简单安全机制。 This is built into mysql PHP drivers, and is not something you can bypass. 这是内置在mysql PHP驱动程序中的,您不能绕过它。 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 ....');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM