views:

37

answers:

4

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?

+2  A: 

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. 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';
}
Alec
A: 

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";
}
ITroubs
the count is needed only if the "starting the stuff" and the "ending the stuff" is required to show only in case the result set would not be empty
ITroubs
disagree - I think that OP wants a viable way of returning a different output if there are no results returned. Counting the rows is perfectly fine.
Thomas Clayson
i never said it wasn't fine to count the rows. if it realy matters how many rows he has and if the resulting rowset isn't empty then the count shurely makes sense
ITroubs
A: 

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
}
Thomas Clayson
A: 

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 />';
    }
}
Aether