Function does not return correct resource
I have this function:
function query_dp($sql) {
$link = mysql_connect('localhost', $bd_id, $bd_pass);
mysql_select_db("$bd"开发者_JS百科);
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 an... integer? WTF?
Any help would be greatly appreciated!
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.
your call to mysql_close means that you no longer have a link to the mysql resource that you need in mysql_num_rows
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.
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();
精彩评论