简体   繁体   中英

While loop working only once inside for each php

This is my Code. I know, the while loop will work only once. But foreach does not loop after fetching one value, ie if I am selecting 3 checkboxes. Only one will pass the values.

if(!empty($_POST["list"]))  
      {  
$connect = @mysql_connect("localhost","***","***") or die (" this error");
mysql_select_db("edu_info")or die ("database does not exist"); 


          foreach($_POST["list"] as $list=> $val)  
           {  


$query=mysql_query("select * from students where id='$val' limit 1");

while($row=mysql_fetch_assoc($query))
{
$user=$row['username'];
$number=$row['pphone'];
$name=$row['name'];
$pname=$row['pname'];
}
echo $user;
echo $number;
echo $name;
echo $pname;
    }
    }

This is my checkbox in html. The number of checkboxes is not fixed, it depends upon the query.Code below is just to get multiple checkboxes

    {
        <input type="checkbox" name="list[]" value="<?php echo $id; ?>
    }

Why is foreach not fetching values from all the selected checkboxes. Please help. Thanks in advance. :)

It looks to me like your while loop is overwriting the values each time. I don't see where you're doing anything with the values you retrieve, hence, for example:

$user=$row['username'];

may be executing three times, but each time overwriting the previous value. It's always giving you the last value chosen, right? If so, that's because you're setting $user three times, and only after the last one are you doing anything with it.

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