简体   繁体   English

PHP + mysql_num_rows

[英]php + mysql_num_rows

is there a more efficient way of doing the following? 有没有更有效的方法来进行以下操作?

$total_a = mysql_query("SELECT `id` FROM `table` WHERE `this` = 'that'");
$total_b = mysql_num_rows($total_a);

if(!$total_b)
{
    echo 'no results';
}
else
{
    $a = mysql_query("SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC");
    while($b = mysql_fetch_assoc($a))
    {
        echo $b['id'].'-'.$b['time'].'<br />';
    }
}

there is no other way around than using two queries for this, is there? 除了使用两个查询之外 ,没有其他办法了吗?

You're retrieve the same thing twice now, right? 您现在两次检索相同的东西,对吗? If some data exists according to query 1, retrieve that data again with query 2 and display it. 如果根据查询1存在一些数据,请通过查询2再次检索该数据并显示它。 Why not simply use the second query? 为什么不简单地使用第二个查询?

$sql = "SELECT id, time FROM table WHERE this = 'that' ORDER BY time DESC";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
  while ($b = ...) {
    ...
  }
} else {
  echo 'no results';
}

You should be able to reuse the query like so: 您应该能够像这样重用查询:

$result = mysql_query("SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC");
$num_rows = mysql_num_rows($result);

if(!$num_rows)
{
    echo 'no results';
}
else
{
    while($row = mysql_fetch_assoc($result))
    {
        echo $row['id'].'-'.$row['time'].'<br />';
    }
}

Fundamentally they are the same query are they not?! 从根本上说,它们是相同的查询,不是吗?

Why can't you do: 你为什么不能做:

$sql = "SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC";
$result = mysql_query($sql);

if(mysql_num_rows($result)){
    while($b = mysql_fetch_array($result))
    {
        echo $b['id'].'-'.$b['time'].'<br />';
    }
}
else{
  // no rows
}

just use: 只需使用:

$a = mysql_query("SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC");
while($b = mysql_fetch_assoc($a))
{
    echo $b['id'].'-'.$b['time'].'<br />';
}

why counting? 为什么要计数?

you only should count the possible rows if you do something like 如果执行类似的操作,则只应计算可能的行数

if($count){
echo "starting the stuff";
$a = mysql_query("SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC");
while($b = mysql_fetch_assoc($a))
{
    echo $b['id'].'-'.$b['time'].'<br />';
}
echo "ending the stuff";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM