tags:

views:

69

answers:

4
$output = "<loginsuccess>";

for( $i = 1; $row = mysql_fetch_array($result); $i++ )          {


$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
}

$output .= "</loginsuccess>";

I need now a simple condition where if the result is empty then i need to return no inside the xml [ login success ].

Is this a correct way....

if($row = mysql_fetch_array($result))          {

for( $i = 1; $row = mysql_fetch_array($result); $i++ )          {

$output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
} } else { 
    $output.="no"; 
}
+2  A: 
if (mysql_num_rows($result) == 0) { 
  $output .= '<loginsuccess>no</loginsuccess>';
} else {
  // your code
}
Schnalle
== 0? Are you serious? ;)
Greg
@Greg *5* : )
Ólafur Waage
@greg: touché! ;)
Schnalle
+1  A: 

Try this instead:

$i = 1;

while($row = mysql_fetch_array($result))
{
    $output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";

    $i++;
}

if ($i == 1)
    $output .= "no";
Greg
are you serious? if $i==1? you forgot the `goto` somewhere.
Schnalle
Why on earth would anyone downvote this?
Ólafur Waage
Yes if $i == 1, the while loop never ran and the result is empty.
Ólafur Waage
of course it works, but it's spaghetti.
Schnalle
I don;t really see any problems with this, just make sure no code ends up between the $i=1, the while loop and the if($i==1).
Pim Jager
Given the original code I was working on the assumption $i was used in the loop and had been chopped out for the Q. If $i isn't needed then you could do it a bit differently.
Greg
A: 

Wont the for-loop simply be skipped when there are no rows? Otherwise you might want to use mysql_num_rows to count the number of rows in your result set.

Martin Geisler
+1  A: 

Just a quick note, I would do what Schnalle does, but in your code I would change the for loop to a while loop as you are not doing anything with the $i

while($row = mysql_fetch_row($result)){

In total I would write you code like this:

$output = '<loginsucces>';
if(mysql_num_rows($result)){
  while($row = mysql_fetch_row($result)){
    $output .="<keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur><queryTime>".(substr($end_time-$start_time,0,5))."</queryTime>";
  }
} else {
  $output .= 'no';
}
$output .= '</loginsucces>';

Also It owuld be even better not to mix logic and output, but that would be overkill in this situation.

Pim Jager