tags:

views:

86

answers:

5

Hi there,

I was wondering if this

$c = mysql_num_rows(mysql_query("select * from action_6_weekly where code='$code'"));

is considered valid PHP?

Or do I need to do the following?

$r = mysql_query("select * from action_6_weekly where code='$code'");
$c = mysql_num_rows($r);

this is what i am actually doing:

if($entry == '9')
    $c = mysql_num_rows(mysql_query("select * from action_6_5pts where code='$code'")) or die ('MYSQL ERROR: '.mysql_error().' in '.__FILE__.' on '.__LINE__.'.');
elseif($entry == 'a')
    $c = mysql_num_rows(mysql_query("select * from action_6_10pts where code='$code'")) or die ('MYSQL ERROR: '.mysql_error().' in '.__FILE__.' on '.__LINE__.'.');
else
    $c = mysql_num_rows(mysql_query("select * from action_6_weekly where code='$code'")) or die ('MYSQL ERROR: '.mysql_error().' in '.__FILE__.' on '.__LINE__.'.');

if($c > 0) 
    $waiting_for_reply = false;
+1  A: 

Yes, you can use the return value of one function as a parameter value for another function. So in your case both variants are equal.

But you need to be careful when doing that as part of a condition that might be tested multiple times like in a while loop. Because the condition in the following is executed with every iteration:

while ($row = mysql_fetch_assoc(mysql_query("SELECT …"))) {
    // …
}

This will yield an infinite loop as mysql_query("SELECT …") is executed with every iteration and will probably return a valid result set every time.

But you shouldn’t select all data if you just want to get the number of rows. Use the aggregate function COUNT to let MySQL count the rows for you.

Gumbo
+4  A: 

It is generally better to do it on separate lines and assign it a variable.

This way you can work with the result easier. But to get a count of rows, if that is all you are looking for, this would be better and more efficient:

$r = mysql_query("select count(id) from action_6_weekly where code='$code'");
$c = mysql_result($r, 0, 0);

Where the id is the unique identifier field to count.

EDIT: Given that you do not care how many rows there are, just that it exists:

$r = mysql_query("select code from action_6_weekly where code='$code' LIMIT 1");
if (mysql_num_rows($r) > 0) {
    // echo it exists!
}
Brad F Jacobs
+5  A: 
Mchl
A: 

It is about readability and brevity though you can use either, I would go with this one though because it looks cleaner:

$r = mysql_query("select * from action_6_weekly where code='$code'");
$c = $c = mysql_num_rows($r);
Sarfraz
A: 

Variables are placeholders for data. Therefore, if you can write

$x = 4;
function($x);

you can also write

function(4);

But it's easier to later commit changes and add data the former way. Comments also help.

XLR3204S