Looping through query results multiple times with mysqli_fetch_array?

杀马特。学长 韩版系。学妹 提交于 2019-12-25 11:44:09

问题


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).


回答1:


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'];



回答2:


You could use the mysqli_fetch_all function to return all results as an array, which you could then manipulate as you would any other array in PHP:

$arr = mysqli_fetch_all($namesList);


来源:https://stackoverflow.com/questions/22565844/looping-through-query-results-multiple-times-with-mysqli-fetch-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!