简体   繁体   中英

While-loop after SQL query won't work PHP

$mysqli_query = mysqli_query($mysqli, "SELECT * FROM ".$snt_stone." ");   
        while($result = mysqli_fetch_array($mysqli_query)){

        $DatabaseID = $result['DatabaseID'];
        $ItemName = $result['ItemName'];
        $ItemStatus = $result['ItemStatus'];
        $ItemCategory = $result['ItemCategory'];

        }

I have multiple things in my database but for some reason my while loop only loops once. How can I make it loop through every item/row once?

Your problem is that you don't understand how while loop works.

while($result = mysqli_fetch_array($mysqli_query)){
$DatabaseID = $result['DatabaseID'];
}

This loop gives value of $result['DatabaseID']; to variable $DatabaseID . When you loop second time $DatabaseID has its value changed again.

Thus what you basically do is run through the results of your SELECT query and every time give the values you fetched to the group of particular variables overwritting them each time you go through the loop.

You can check your logic error by running this:

while($result = mysqli_fetch_array($mysqli_query)){

   echo $result['DatabaseID'];
   echo $result['ItemName'];
   echo $result['ItemStatus'];
   echo $result['ItemCategory'];

   $DatabaseID = $result['DatabaseID'];
   $ItemName = $result['ItemName'];
   $ItemStatus = $result['ItemStatus'];
   $ItemCategory = $result['ItemCategory'];

    }

You will see that echo gives all the results from select but since you keep on overwritting the variable only the last value is saved.

EDIT

I think that the simplest solution to your problem would be save the values you need as an array and then work with the array. The simplest way to do it would be:

$mysqli_query = mysqli_query($mysqli, "SELECT * FROM ".$snt_stone." ");   
        while($result = mysqli_fetch_array($mysqli_query)){

        $DatabaseID[] = $result['DatabaseID'];
        $ItemName[] = $result['ItemName'];
        $ItemStatus[] = $result['ItemStatus'];
        $ItemCategory[] = $result['ItemCategory'];

        }

Then you can run print_r($DatabaseID) to print the array content.

Such constructed array would be rather unhandy to use, check php's manual on arrays and create one that would best fill your needs: http://php.net/manual/en/function.array.php

Of course it also depends on what you want to do with those values later on in your code.

 $mysqli_query = mysqli_query($mysqli, "SELECT * FROM ".$snt_stone." ");   
    while($result = mysqli_fetch_array($mysqli_query)){

       echo  $result['DatabaseID'];
       echo $result['ItemName'];
       echo $result['ItemStatus'];
       echo $result['ItemCategory'];

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM