I am trying to add random x
and y
values to a MySQL database but strangely it only seems to ever add one value. I was looking at many of the other posts of similar issues on Stackoverflow and it just seemed they did not have query within the loop was the common issue. I do have the query in the loop and am unsure why it is still not working.
Please see my code below:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y)"
$sql .= "VALUES ($x, $y);";
//mysql_query($sql);
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
I edited your for loop to look something like this, and it worked perfectly fine for me.
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y) VALUES ('$x', '$y')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Successfully created record " . $i;
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
ob_start();
ob_flush();
flush();
usleep(001000);
ob_flush();
flush();
}
it Delay's the loop by just a little like a fifth of a second in total. The reason I have delayed the iteration is because your database might have a limit on how many queries can be sent within a time frame. It works for me let me know if it works for you.
Create the values array in the for loop, then use implode to build the query outside the loop.
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO data (x, y) VALUES ";
$values = [];
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$values[] = "($x, $y)";
}
$query = $sql . implode(",", $values) . ";";
$r = $conn->query($query);
if ($r) {
echo "New records created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->connect_error;
}
$conn->close();
You are just running a single query for each loop. No need for multi query
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y)"
$sql .= "VALUES ($x, $y);";
//mysql_query($sql);
if (mysqli_query($conn,$sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}