簡體   English   中英

PHP/MYSQL while 循環問題

[英]PHP/MYSQL while loop problem

<?php
include 'db.php';
$i=0;
$result15=mysql_query("select c.dishes from c");
 while($row=mysql_fetch_array($result15))
{
  if($row['dishes']!=NULL)
  {
  $dish[$i]=$row['dishes'];
 $i++;
}

}

  //$j=0;
 //while($j<$i)
 $j=0;
 while($j<$i)
 {

$result16=mysql_query("select * from dish_box where dish_name='$dish[$j]'");
while($row=mysql_fetch_array($result16))
{
    $v_id=$row['dish_id'];
    echo $v_id.'<br />';
}
$j++;

 }

 mysql_close();
 ?>

這個 while 循環只回顯一次值。 請弄清楚為什么循環一次就可以工作?

也許更好的解決方案:

// if you're using user input here, be sure to use mysql_real_escape_string
/*
  $dishes = "'";
  foreach( $dish as $key => $val ) 
       $dishes .= "'" . mysql_real_escape_string( $val ) . "',";
  $dishes = substr( $dishes, 0, strlen( $dishes ) -2 ); // remove last ,
*/
// otherwise implode the list
$dishes = "'".implode("','", $dish)."'";

// in either case use the IN operator
// the semi-colon that was in the query won't work.
$result16=mysql_query("select * from dish_box where dish_name in ($dishes)");
// to confirm how many rows
echo "result16 returned " . mysql_num_rows($result16) . 'rows.';
while($row=mysql_fetch_array($result16))
{
    $v_id=$row['dish_id'];
    echo $v_id.'<br />';
}

我剛剛記得你在另一個問題中做了類似的事情。 您實際上可以結合這兩個查詢並節省一些時間:

$result16=mysql_query("select * from dish_box where dish_name in ".
                      "(select c.dishes from c)");
while($row=mysql_fetch_array($result16))
{
    $v_id=$row['dish_id'];
    echo $v_id.'<br />';
}

您存儲在$result16中的查詢很可能只返回一行。 嘗試做:

$result16 = mysql_query(...);
echo "Total rows: ", mysql_num_rows($result16), "<br />";
while (...) {
etc.....

同樣,您可能想嘗試這樣做:

$result16 = mysql_query(...) or die(mysql_error());

假設您的查詢已成功,只會在事情失敗時造成痛苦。

     $i=5;   
$j=0;
while($j<$i)
{

$result16=mysql_query("select * from dish_box where dish_name='$dish[$j]'");
while($row=mysql_fetch_array($result16))
{

$v_id[]=$row['dish_id'];
}
$j++;

}
var_dump($v_id);

您正在用每個循環覆蓋 $v_id 的值 - 因此它只會返回最后一個值。 使 $v_id 成為一個數組並寫入它會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM