我有以下的PHP代碼的MySQL/PHP插套LAST_INSERT_ID()
$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);
當我嘗試執行這個代碼,這個錯誤發生:
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
要測試是否有錯誤使用mySql語法,我將字符串放在一個文件中,並直接使用:mysql -u root -p myDatabase < InsertSqlStatement.sql
執行該語句時沒有任何問題。
我的PHP代碼有什麼問題?
如何'@petID work'的範圍是什麼?如果我做了一個查詢來設置petID,下面的'mysqli_query'能夠撿起它嗎? – Rhs