Reputation: 189
I would like to update my users database with a 4 digit random number.
I seem to have got stuck, on the bit for the loop, so that it will give a different random number to each user in the database. So far i have this.
$newpincode = array(sprintf("%04d",mt_rand(0,9999)));
$users_sql = "SELECT * FROM wifi_users";
$result_users = mysql_query($users_sql) or die(mysql_error());
while($row = mysql_fetch_array($result_users)){
foreach ($newpincode as $pin) {
$sql = "UPDATE wifi_users SET `pincode` = '" . $pin . "' WHERE id = '" . $row['id'] . "'";
$resultCount = mysql_query($sql) or die(mysql_error());
$count = mysql_fetch_assoc($resultCount);
}
}
Upvotes: 0
Views: 876
Reputation: 71384
Why not just run a single query:
UPDATE wifi_users SET `pincode` = LPAD(FLOOR(RAND() * 10000), 4, '0')
Note this doesn't guarantee uniqueness, but then again neither does your current code. 4 digits doesn't give you enough values to provide uniqueness anyways if you plan on having more than 10000 users.
Upvotes: 3
Reputation: 173572
The problem is that the same pin code is given to all users.
Also, your inner loop would theoretically update the same record multiple times, although in this case that only happens once per record.
To issue a new pin code for each record, you have to move the pin code generation inside the outer loop and remove the inner loop.
As an aside, consider using PDO and prepared statements.
Upvotes: 0
Reputation: 4511
If you're looking for a unique random number for each user check this out: How to Generate Random number without repeat in database using PHP?
Upvotes: 1