如果使用if(empty($ variable)),如何返回所有行?

时间:2011-09-22 13:59:47

标签: php

我在下面使用此查询,如果我只使用if(empty($ field1))来显示,它只返回条目中的第一个查询。如果我填写打印(“”);它工作,但我想使用if(empty($ field1))片段来显示。我该怎么办?

$sql="SELECT field1, field2 FROM table WHERE p_id='$pid'
      and k_id='$kid' ORDER BY id DESC";  
$result=mysql_query($sql);

$query = mysql_query($sql) or die ("Error: ".mysql_error());

if ($result == "")
{
    echo "";
}

echo "";

$rows = mysql_num_rows($result);

if($rows == 0)
{
    print("");
}
elseif($rows > 0)
{
    while($row = mysql_fetch_array($query))
    {
        $field1 = $row['field1'];
        $field2 = $row['field2'];
        print("");
    }
}

if (empty($field1)) {
    echo ""; //Thats right, i don't want anything to show for this portion
} else {
   echo "<div id=comments>Comments</div><br>
   <div id=entries>$field1 and $field2</div>";
}

2 个答案:

答案 0 :(得分:2)

你想做什么?像这样的东西:

$sql="SELECT field1, field2 FROM table WHERE p_id='$pid' and k_id='$kid' ORDER BY id DESC";  
$result=mysql_query($sql)  or die ("Error: ".mysql_error());
$rows = mysql_num_rows($result);

if ($rows > 0)
  echo "here are your entries\n";

while($row = mysql_fetch_array($result))
{
    echo $row['field1']." ";
    echo $row['field2']."\n";
}

另一种方式

$sql="SELECT field1, field2 FROM table WHERE p_id='$pid' and k_id='$kid' ORDER BY id DESC";  
$result=mysql_query($sql)  or die ("Error: ".mysql_error());
$rows = mysql_num_rows($result);

if ($rows > 0)
  echo "here are your entries\n";

while($row = mysql_fetch_array($result))
{
    if (empty($row['field1'])) {
        echo " ";
    } else {
    echo $row['field1']." ";
    echo $row['field2']."\n";
    }
}

答案 1 :(得分:1)

我相信mysql_fetch_array只返回一行 http://www.w3schools.com/PHP/func_mysql_fetch_array.asp

还确定p_id和k_id都不是唯一的吗?

我也会尝试$ sql =“SELECT * FROM table WHERE p_id ='$ pid'       和k_id ='$ kid'ORDER BY ID DESC“;

只是为了看看是否会产生任何不同的结果,你总是可以从返回数据中解析出两个字段

尝试开始($ results变量只是令人困惑的事情):

  $sql="SELECT field1, field2 FROM table WHERE p_id='$pid'
      and k_id='$kid' ORDER BY id DESC";  

      $query = mysql_query($sql) or die ("Error: ".mysql_error());

   $rows = mysql_num_rows($query);

  if($rows == 0)
  {
  print("");

  }else{

  while($row = mysql_fetch_array($query))
   {
          if ($row['field1'] == "")
            {
               print("");
            }else{
           $field1 = $row['field1'];
           print($field1)
            }

if ($row['field2'] == "")
            {
               print("");
            }else{
           $field1 = $row['field2'];
           print($field2)
            }
  }

}