Updating a database with a loop


Updating a database with a loop



I have added a new column to a database and want to insert random values as temporary accesskeys into all rows. This is what I have (yes, I know there is no error reporting - can add that later):


require ('./connect.php');
$length = 10;
$db = mysqli_connect($db_hostname,$db_username,$db_password,"paratb_members");
$result = mysqli_query($db,"SELECT * FROM membervote where accesskey = ''");
while ($row = mysqli_fetch_array($result)) {
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
mysqli_query($db,"UPDATE membervote SET accesskey = '$randomString' WHERE accesskey = ''");
echo $row['fname']. " - $randomString<br>";
}



While the echo gives me a unique value for each row, the database rows are all the same first value. Have tried using diffetrent WHERE values but then I get nothing written to the database, but as before the echo is good.



What am I missing? Thanx





1) You assign the always the same $randomString and 2 ) once you have updated the rows with accessKey ='' this condition is not more true and then your where condition fails
– scaisEdge
Jul 1 at 6:46





1 Answer
1



I think the problem is that your UPDATE is setting /every/ row that has a blank accesskey - thus, the first time round the loop, it is setting every row to the same value, and subsequently there are no blank accesskeys left to change.



(Unwise in my opinion to leave exception handling until later, since in my experience it is at its most useful when you first start writing the code.)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API