php嵌套while循环。内循环只能工作一次
问题描述:
这是代码。任何帮助?php嵌套while循环。内循环只能工作一次
<?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;
?>
答
我认为你需要重新查询RES2外环内,或至少复位指针。第二次通过外部循环,你在res2中没有剩下任何东西,因为你已经到了最后
另外,如果你在外部循环中设置res2查询并且添加一个where子句,以便您只与res1中当前行的类别ID匹配。
希望这会有所帮助。
答
广场这里面第一个循环:
$sql2 = "select category_id1,product_id from product";
$res2 = mysql_query($sql2);
+1
也许最好在循环之后使用'mysql_data_seek($ res2,0)'这样的东西,并且删除你的帖子中的两行而不是每次查询数据库? – Class 2014-12-05 06:26:11
答
试试这个:
<?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;
?>
+0
这将在外部循环的每次迭代中重新查询数据库。用'mysql_data_seek($ res2,0);'重置指针会更好 – lordvlad 2014-12-05 10:34:08
你怎么知道内循环运行一次?请解释更多 – madforstrength 2014-12-05 06:12:33
更新查询仅适用于第一个类别编号 – Bibin 2014-12-05 06:14:25
难道您不能通过加入来获得像'ON category_id1 = category_code'这样的项目,然后使用while while循环吗? – Class 2014-12-05 06:22:15