I'm inserting data into a MySQL Table using a for loop in PHP. I'm generating a random ID for $botid
and then inserting it based on the amount of $botsToAdd
.
The loop itself works but the $botid
is always inserted with the same value. So on the first iteration of the for loop if it generated an ID of 2147483647
then all subsequent inserts are inserting with 2147483647
instead of the new $botid
.
My code:
if ($botsToAdd > 0) {
//Disable autocommit
mysqli_autocommit($con, FALSE);
//For loop for $botsToAdd
for ($i = 0; $i < $botsToAdd; $i++) {
//Generate a unique bot ID (integer) that is 11 digits long
$botid = rand(10000000000, 99999999999);
//Insert the bot into the cube_checkin table
$stmt = $con->prepare('INSERT INTO cube_checkin (cube_id, user_id, is_bot) VALUES (?, ?, 1)');
$stmt->bind_param('ii', $cubeid, $botid);
$stmt->execute();
$stmt->close();
}
//Commit the transaction
if (mysqli_commit($con)) {
http_response_code(200);
header('Content-Type: application/json');
echo json_encode(array("success" => "Bots have been added to the cube!"));
exit();
} else {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(array("error" => "There has beeen an error adding bots to the cube."));
exit();
}
}
I really cannot understand why it's behaving like this as I am closing the statement within the loop.