Saturday, August 3, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...