[英]php + mysql_num_rows
有沒有更有效的方法來進行以下操作?
$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 />';
}
}
除了使用兩個查詢之外 ,沒有其他辦法了嗎?
您現在兩次檢索相同的東西,對嗎? 如果根據查詢1存在一些數據,請通過查詢2再次檢索該數據並顯示它。 為什么不簡單地使用第二個查詢?
$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';
}
您應該能夠像這樣重用查詢:
$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 />';
}
}
從根本上說,它們是相同的查詢,不是嗎?
你為什么不能做:
$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
}
只需使用:
$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 />';
}
為什么要計數?
如果執行類似的操作,則只應計算可能的行數
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.