php嵌套while循环。内环只能工作一次

时间:2014-12-05 06:06:47

标签: php mysql while-loop nested

这是代码。任何帮助?

<?php  

    //connect to the database 
        $con=mysql_connect("localhost","root","") or die("Error in connection");
        mysql_select_db("riffadb",$con)or die("Error in database");
    // 
        $sql1 ="select category_id,category_code from category";
        $res1 = mysql_query($sql1); 

        $sql2 = "select category_id1,product_id  from product";
        $res2 = mysql_query($sql2);
        $i=0;
        $j=1000;
        while($row1 = mysql_fetch_array($res1))
        {
            echo $row1['category_code'];
            echo '<br/>';
            while($row2 = mysql_fetch_array($res2))
            {   
                if($row1['category_code'] == $row2['category_id1'])
                {   
                    $sql3 = "update product set category_id = ".$row1['category_id']." where product_id = ".$row2['product_id'];
                    echo '<br/>';
                    mysql_query($sql3);
                }
            }
            $i++;
        }
        echo $i;
    ?>

3 个答案:

答案 0 :(得分:1)

试试这个:

<?php  

//connect to the database 
    $con=mysql_connect("localhost","root","") or die("Error in connection");
    mysql_select_db("riffadb",$con)or die("Error in database");
// 
    $sql1 ="select category_id,category_code from category";
    $res1 = mysql_query($sql1); 


    $i=0;
    $j=1000;
    while($row1 = mysql_fetch_array($res1))
    {
        echo $row1['category_code'];
        echo '<br/>';
          // execute second query under the first loop
         $sql2 = "select category_id1,product_id  from product";
         $res2 = mysql_query($sql2);

        while($row2 = mysql_fetch_array($res2))
        {   
            if($row1['category_code'] == $row2['category_id1'])
            {   
                $sql3 = "update product set category_id = ".$row1['category_id']." where product_id = ".$row2['product_id'];
                echo '<br/>';
                mysql_query($sql3);
            }
        }
        $i++;
    }
    echo $i;
?>

答案 1 :(得分:0)

我认为你需要在外部循环中重新查询res2,或者至少重置指针。第二次通过外部循环,res2中没有任何内容,因为你已经到了结尾

此外,如果在外部循环中设置res2查询并添加where子句,那么只会匹配res1中当前行的类别ID,效率会更高。

希望这有帮助。

答案 2 :(得分:0)

将其置于第一个循环中:

$sql2 = "select category_id1,product_id  from product";
$res2 = mysql_query($sql2);