Peter Peter - 25 days ago 8
MySQL Question

Insert statement after user registration with loop

I have registration form which works fine. Now I want to add second query after user is registered. This query should have loop and add exactly 10 new rows in another table. This is the query with loop

if ($conn->query($sql) === TRUE) {
$result = "Request successfully submitted.";

$new_id = $db_con->lastInsertId();

$qty=11;

$sql = "INSERT INTO new_customer (user_id,value1,value2) VALUES";

for($i=0;$i< $qty;$i++){
$sql .= "($new_id,'1','0')";
if($i < ($qty -1 )){
$sql .=",";
}
}
}


I'm not sure if this is correct way of doing this. After user is successfully registered I'm trying to get lastInsertId and loop and insert 10 new rows in
new_customer
table.

What is happening is that user is successfully registered but nothing is saved in
new_customer
. What is the problem here?

Answer Source

You need to execute your inner query like below:-

$conn->query($sql);

Add it after inner for loop code.

Also if you are using mysqli_* then you need to use mysqli_insert_id:-

$new_id = $db_con->mysqli_insert_id;