tags:

views:

89

answers:

4

Guys, hi. I have this fuctions:

function query_dp($sql){

    $link = mysql_connect('localhost', $bd_id, $bd_pass);
    mysql_select_db("$bd");

    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }


    return mysql_query($sql) or die(mysql_error());

    mysql_close($link);

}
?>

In the main program, when i try to do:

echo mysql_num_rows(query_db($sql));

I get as return

1

When I do not encapsulate that code in a function and use it directly to the main program, i get the number of rows fetched.

The function is not returning a Resource but a... integer? WTF?

Any help would be greatly appreciated!

Thanks!!

A: 

This doesn't directly answer your question, but you shouldn't use the original mysql interface. it is clunky and procedural. Take a look at the mysqli interface. Don't try to wrap the old functions if you have a language supported standard that already does this :D

You above code just becomes

$m = new MysqlI(...);
$rc = $m->query(...);
echo $rc->num_rows();
Byron Whitlock
+1  A: 

your call to mysql_close means that you no longer have a link to the mysql resource that you need in mysql_num_rows

seengee
You can't close a connection after a return ;)
Byron Whitlock
+1  A: 

The problem is in "or" operator. Your function returns result of "mysql_query($sql) or die(mysql_error())" expression, which is 1 or 0. I suggest you to use something like this:

$query_result = mysql_query($sql);
if (!$query_result) {
    die(mysql_error());
}
return $query_result;

Also last line of this function "mysql_close($link)" is never called.

Ivan Nevostruev
Wrong, the 'OR DIE' PHP trick has been valid since v.3.0. Search SO, there is a relevant question. Though I have to admit it is a very bab habit.
Anax
Please try to run code from http://pastebin.com/m4301f239. You'll see `bool(true)`, but not the `string(6) "string"`
Ivan Nevostruev
This how the OR operator works. In the case of function thing() it is evaluated as TRUE (or actually as NOT FALSE, see http://www.php.net/manual/ro/language.types.boolean.php), therefore the DIE part is never executed.This is the same with mysql_connect function. If the connection fails the shortcircuit OR operator chooses the second part (DIE).
Anax
That's exactly why `return mysql_query($sql) or die(mysql_error());` will never return sql statement result
Ivan Nevostruev
+3  A: 

Your variables $bd_id, $bd_pass and $bd are not visible inside the function since they are probably declared in the global scope and not the local scope of that function.

You would either make the global variables accessible by using the global keyword, by using the $GLOBALS variable, or by passing them to the function.

Gumbo