运行2个sql语句2个不同的表(Run 2 sql statement 2 different tables)

编程入门 行业动态 更新时间:2024-10-25 22:23:23
运行2个sql语句2个不同的表(Run 2 sql statement 2 different tables)

我的数据库中有2个表

表用户 user_id auto

table2画廊 id auto 用户名

当用户在将信息插入用户表时进行注册时,我想将user_id发送到gallery user_id字段。

我尝试了以下内容

$connection = dbconnect(); $stmt = $connection->prepare('INSERT INTO users(user_email, username, user_pwd) VALUES (?,?,?)'); $stmt->bind_param('sss', $email, $username, $password); $stmt->execute(); $stmt->close(); $connection = dbconnect(); $last_row = mysqli_insert_id($connection); $connection = dbconnect(); $stmt2 = $connection->prepare('INSERT INTO gallery(user_id) VALUES (?)'); $stmt2->bind_param('s', $last_row); $stmt2->execute(); $stmt2->close();

I have 2 tables in my database

table users user_id auto

table2 gallery id auto user_id

when the user register while it inserts the info to the user table,which works I want to send the user_id to the gallery user_id field.

I have tried the following

$connection = dbconnect(); $stmt = $connection->prepare('INSERT INTO users(user_email, username, user_pwd) VALUES (?,?,?)'); $stmt->bind_param('sss', $email, $username, $password); $stmt->execute(); $stmt->close(); $connection = dbconnect(); $last_row = mysqli_insert_id($connection); $connection = dbconnect(); $stmt2 = $connection->prepare('INSERT INTO gallery(user_id) VALUES (?)'); $stmt2->bind_param('s', $last_row); $stmt2->execute(); $stmt2->close();

最满意答案

首先,您不需要创建新连接来获取最后一个插入ID。 相反,你可以这样做:

$stmt = $connection->prepare('INSERT INTO users(user_email, username, user_pwd) VALUES (?,?,?)'); $stmt->bind_param('sss', $email, $username, $password); $stmt->execute(); $last_row = $stmt->insert_id; $stmt->close(); $connection = dbconnect(); $stmt2 = $connection->prepare('INSERT INTO gallery(user_id) VALUES (?)'); $stmt2->bind_param('s', $last_row); $stmt2->execute(); $stmt2->close();

另外,如果你的user_id是一个整数,你可以将$last_row绑定为“i”。

除此之外,您应该显示您在问题中得到的错误。

First of all, you don't need to create a new connection to get last insert id. Instead you can do it like:

$stmt = $connection->prepare('INSERT INTO users(user_email, username, user_pwd) VALUES (?,?,?)'); $stmt->bind_param('sss', $email, $username, $password); $stmt->execute(); $last_row = $stmt->insert_id; $stmt->close(); $connection = dbconnect(); $stmt2 = $connection->prepare('INSERT INTO gallery(user_id) VALUES (?)'); $stmt2->bind_param('s', $last_row); $stmt2->execute(); $stmt2->close();

Also, if your user_id is an integer, you could bind the $last_row as "i".

Other than these, you should show the error you're getting in your question.

更多推荐

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

发布评论

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

>www.elefans.com

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