John Davidson

php - Each row has the same random number being inserted

0 comments
Message:


I'm looking to insert random numbers into each column in a database.


The issue that is occuring is that each column for some reason has the same random generated value being passed inside.


$sql = "SELECT * FROM players";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
$targScore = 3;
while($row = $result->fetch_assoc()) {

$target = 3; // The target number the sequence is adding up to
$n = 4; // Max numbers within sequence

while ($n) {
if (1 < $n--) {
$addend = rand(0, $target - ($n - 1));
$target -= $addend;
$num[] = $addend;
} else {
$num[] = $target;
}
}

/* Rows to update */
/* Output looks like:
[0] = 1
[1] = 2
[0] = 0
[0] = 1
*/
$changeScore = "UPDATE players SET doja='$num[0]' WHERE score='$targScore'";
$conn->query($changeScore);

$changeScore = "UPDATE players SET 7acres='$num[1]' WHERE score='$targScore'";
$conn->query($changeScore);

$changeScore = "UPDATE players SET tweed='$num[2]' WHERE score='$targScore'";
$conn->query($changeScore);

$changeScore = "UPDATE players SET bickel='$num[3]' WHERE score='$targScore'";
$conn->query($changeScore);
}
}

The data looks like: https://i.stack.imgur.com/5mQMO.jpg


What I need is that each loop, it will run the randomizer again but change the numbers its inserting so that each row will have different numbers.



My Answer:
"INSERT INTO table_name (column1, column2, column3) VALUES ";

for ($i = 0; $i < 10; $i++) {
$randomNumber = rand(1, 100);
$sql .= "($randomNumber, $randomNumber, $randomNumber), ";
}

$sql = rtrim($sql, ", ");

// Execute the SQL query to insert the random numbers into the database
// mysqli_query($connection, $sql);

Rate this post

5 of 5 based on 5383 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us