简体   繁体   中英

Nested while loop in PHP is not working for MySQL database queries

All the whole day I'm trying to solve this problem but still no luck.

The scenario is: I am developing a vertical menu which should query groups and items of those groups in a menu respectively, but groups are being populated without its items.

Code was written in the following way:

$data1 = mysql_query(select groupnames from groups where categoryy='Agriculture');

while($info1=mysql_fetch_array($data1))
{

    echo $info1[0];
    $data2==mysql_query(select itms from groupitems where categoryy='Agriculture' and    groupname='$info1[0]');
    while($info2=mysql_fetch_array($data2))
    {
    echo $info2[0];
    }
}

In the above code, groups are being populated nicely but no items from groupitems table are being populated. If I write Grain ( Grain is one of the group of agriculture in my database) instead of groupname=$info1[0] then it works. But it should be got dynamically from the query.

Please help, I'm in trouble.

at last its solved! here's the code:

<?php
include "aPannel/dbconn.php";
$query="select GroupName from categorygroup where categoryy='Agriculture'";

$i=0; 

$result=mysql_query($query);
$num=mysql_num_rows($result);
$groupname=mysql_result($result ,$i ,"GroupName"); 
mysql_close();

if ($num=="0") echo "<p>Sorry, there are no groups to display for this Category.</p>"; 

else 
{ 
echo "<p>There are currently <strong>$num</strong> groups represented in our database.</p><br>"; 

while($i < $num) 
{
    $groupname=mysql_result($result ,$i ,"GroupName"); 
    include("aPannel/dbconn.php");
    $query2 = "SELECT subcategory FROM groupsubcategory WHERE groupname='$groupname'"; // count number of items in each group 
    echo $query2 . "<br/>"; 
    $resultt=mysql_query($query2);
    $countt=mysql_num_rows($resultt); 
    mysql_close();
    echo $countt . "subcategories" . "<br/>"; // display number of items 
     $i++; 
    } 
} // end if results 
?>

Your queries are not wrapped around double-quotes (" ") . Always remember that what you pass to mysql_query method is a string argument. And also $data2==.... seems wrong.

So, change the code like this

     $data1=mysql_query("select groupnames from groups where categoryy='Agriculture'");

    while($info1=mysql_fetch_array($data1))
    {

        echo $info1[0];
        $infoTemp=$info1[0];
        $data2=mysql_query("select itms from groupitems where categoryy='Agriculture' 
and    groupname='$infoTemp'");
        while($info2=mysql_fetch_array($data2))
        {
        echo $info2[0];
        }
    }

I hope it should work

EDIT: Also are you sure column itms in second query or items ? EDIT: added temporary variable

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