我的数据库中有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.
更多推荐
发布评论