Jump to content

Updating database


cs1h

Recommended Posts

Hi,

 

I want to be able to insert a random number into a column in my database, a different random number needs to be put into each different row but I have over 900 rows and it would take too long to do it manually. 

 

Each row has its own id, does anyone know how I could make an automated program to do this?

 

I hope I explained it well enough.

 

Thanks,

 

Colin

Link to comment
https://forums.phpfreaks.com/topic/91902-updating-database/
Share on other sites

-select all your rows

-cycle through each one

-assign random number( rand() function) to it and run the update query

-put that random number in an array

-the next time you cycle through check the random number with the array to make sure you don't get any duplicates

 

Link to comment
https://forums.phpfreaks.com/topic/91902-updating-database/#findComment-470605
Share on other sites

<?php
$rand = "";
$sql = "SELECT id FROM `table`";
$res = mysql_query($sql) or die(mysql_error());
while($r = mysql_fetch_assoc($res)){
$rand = rand(1,3000);
$update = "UPDATE `table` SET `randomfield` = '$rand' WHERE id = '".$r['id']."' LIMIT 1";
mysql_query($update) or die($mysql_error());
}
?>

 

That is something very simple and doesn't check to see if the random value has a duplicate in the table. for that you could probably:

1. create an array which holds the random values

2. query the table to get the number of rows.

3. run a loop from the result

4. in each loop get the random value and add it to the array

5. once added you can check the rand value being generate against the values in the array.

6. once checked update the row.

 

Ray

Link to comment
https://forums.phpfreaks.com/topic/91902-updating-database/#findComment-470625
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.