从1个表单插入2个表。(Insert into 2 tables from 1 form. Mysql Transaction?)
用户将创建一篇文章并使用它提交图像。
+文章将转到文章表。
+图像将转到图像表(以便可以在网站的其他区域使用)。
有人建议我使用TRANSACTIONS但我收到错误。
$sql ='BEGIN INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW()) INSERT INTO images(article_id, image_caption) VALUES(LAST_INSERT_ID(),?); COMMIT'; $stmt = $conn->stmt_init(); if ($stmt->prepare($sql)) { $stmt->bind_param('sss', $_POST['article_name'], $_POST['description'], $_POST['image_caption']); $OK = $stmt->execute(); printf("%d Row inserted.\n", $stmt->affected_rows); $stmt->free_result(); } else{ echo "Failure- article not uploaded"; }The user will create an article and submit an image with it.
+The article will go to the articles table.
+The image will go to images table (so that it can be used in other areas of the site).
It has been suggested I use TRANSACTIONS but I am getting errors.
$sql ='BEGIN INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW()) INSERT INTO images(article_id, image_caption) VALUES(LAST_INSERT_ID(),?); COMMIT'; $stmt = $conn->stmt_init(); if ($stmt->prepare($sql)) { $stmt->bind_param('sss', $_POST['article_name'], $_POST['description'], $_POST['image_caption']); $OK = $stmt->execute(); printf("%d Row inserted.\n", $stmt->affected_rows); $stmt->free_result(); } else{ echo "Failure- article not uploaded"; }最满意答案
$mysqli->query("START TRANSACTION"); $stmt = $mysqli->prepare('INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW())'); $stmt->bind_param('ss', $_POST['article_name'], $_POST['description']); $stmt->execute(); $stmt = $mysqli->prepare('INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?)'); $stmt->bind_param('s', $_POST['image_caption']); $stmt->execute(); $stmt->close(); $mysqli->query("COMMIT"); $mysqli->query("START TRANSACTION"); $stmt = $mysqli->prepare('INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW())'); $stmt->bind_param('ss', $_POST['article_name'], $_POST['description']); $stmt->execute(); $stmt = $mysqli->prepare('INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?)'); $stmt->bind_param('s', $_POST['image_caption']); $stmt->execute(); $stmt->close(); $mysqli->query("COMMIT");更多推荐
发布评论