我正在尝试启动一个事务是mysql并将数据插入数据库。可以在github here上找到数据库源sql。这是错误:
错误:START TRANSACTION; INSERT INTO Books(Title,PublicationDate, PurchaseDate,Description,LocationID,GenreID)VALUES('简单 Genius','2008-4-1','2009-5-7','','Hardbook Library','Fiction');组 @bookid = LAST_INSERT_ID(); INSERT INTO BookAuthors(FirstName, MiddleName,LastName)VALUES('David','','Baldacci'); SET @authorid = LAST_INSERT_ID(); INSERT INTO AuthorsInBooks(AuthorID,BookID) 价值观(@authorid,@ bookid);承诺;您的SQL中有错误 句法;查看与MySQL服务器版本对应的手册 正确的语法使用'INSERT INTO Books附近(标题, PublicationDate,PurchaseDate,Description,LocationID,'at line 3
靠近'INSERT INTO Books(Title,PublicationDate,PurchaseDate,Description,LocationID')对我来说没有意义,因为它在LocationID之后缺少GenreID。我错过了什么?当我将这段代码复制并粘贴到phpmyadmin时工作正常。我的php版本是5.4。
这是php代码:
$sql = "
START TRANSACTION;
INSERT INTO Books(Title, PublicationDate, PurchaseDate, Description, LocationID, GenreID)
VALUES('".$Title."', '".$YearWritten."','".$YearPurchased."','".$Description."','".$Location."','".$Genre."');
SET @bookid = LAST_INSERT_ID();
INSERT INTO BookAuthors(FirstName, MiddleName, LastName)
VALUES('".$AuthFirstName."', '".$AuthMiddleName."', '".$AuthLastName."');
SET @authorid = LAST_INSERT_ID();
INSERT INTO AuthorsInBooks(AuthorID, BookID)
VALUES(@authorid, @bookid);
COMMIT;
";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
答案 0 :(得分:2)
mysqli_query()
只能执行1个查询,如果要执行多个查询,则需要:
if (mysqli_multi_query($conn, $sql)) {
答案 1 :(得分:2)
回复your comment“我能看到你的意思@eggyal的例子吗?”:
// mysqli provides API calls for managing transactions
mysqli_autocommit($conn, false);
// parameterise variables - NEVER concatenate them into dynamic SQL
$insert_book = mysqli_prepare($conn, '
INSERT INTO Books
(Title, PublicationDate, PurchaseDate, Description, LocationID, GenreID)
VALUES
(?, ?, ?, ?, ?, ?)
');
// bind the variables that (will) hold the actual values
mysqli_stmt_bind_param(
$insert_book,
'siisss', // string, integer, integer, string, string, string
$Title, $YearWritten, $YearPurchased, $Description, $Location, $Genre
);
// execute the statement (you can change the values of some variables and
// execute repeatedly without repreparing, if so desired - much faster)
mysqli_stmt_execute($insert_book);
// mysqli provides API calls for obtaining generated ids of inserted records
$book_id = mysqli_insert_id($conn);
// ... etc ...
// use the API call to commit your transaction
mysqli_commit($conn);
// tidy up
mysqli_stmt_close($insert_book);
请注意,我之前没有包含任何错误检测/处理,您当然希望将其包含在任何实际代码中。