Saturday 3 August 2019

php - Looping through query results multiple times with mysqli_fetch_array?



Does the mysqli_fetch_array() function remove each value as it returns it? If not, how can I go back to the top of the array when I've finished looping through it?



I need to loop through the list several times, as I'm using it to generate unique usernames (by adding numbers to the end if it's already taken).



$uniqueName = true;

while($row = mysqli_fetch_array($namesList)) {
if ($row['Username'] == $UserBase) {

$uniqueName = false;
}
}

$number = 0;
if ($uniqueName == true) {
$User = $UserBase;
}
else {
while ($uniqueName == false) {

$uniqueName = true;
$number++;
$tempList = $namesList2;
while($row = mysqli_fetch_array($tempList)) {
if ($row['Username'] == $UserBase . $number) {
$uniqueName = false;
}
}
}
$User = $UserBase . $number;

}


$namesList is a list of all usernames in the database so far. Basically, $UserBase is the forename and surname of the user added together. What happens at the moment is that $User becomes $Userbase with a 1 on the end, even when it should be 2. However, if it's the first instance of the name then it doesn't add anything (which is working as intended).


Answer



a magic



$data = array();
while ($row = mysqli_fetch_array($res))
{

$data[] = $row;
}

foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];
foreach ($data as $row) echo $row['name'];


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...