从1个表单插入2个表。(Insert into 2 tables from 1 form. Mysql Transaction?)

编程入门 行业动态 更新时间:2024-10-23 21:25:07
从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");

更多推荐

本文发布于:2023-07-05 09:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1035499.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   Insert   tables   Transaction   Mysql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!