Case Case - 1 month ago 9
MySQL Question

Run 2 sql statement 2 different tables

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();

Answer

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.

Comments