Page 1 of 1

mySQL query works, but returns false in PHP

Posted: Tue Aug 24, 2010 12:28 pm
by nimzodisaster
This buggered me an hour last night, maybe someone can tell me what I'm doing wrong. The query fails, with no error. I am connecting properly I believe. This is uber simple so what the heck am I doing wrong. I took the query from phpmyadmin where it returns results properly. This has to be something really simple, but since Im relatively new to php/mySQL I expect to be schooled quickly. Thanks.

Code: Select all

$dbhandle = mysql_connect('localhost', 'root', 'password') or die(mysql_error());
$link =	mysql_select_db('exp', $dbhandle) ;
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully ';

$query =  'SELECT * FROM `uidhistory` WHERE `UID` = 1 LIMIT 0, 30 ';
$result = mysql_query($query, $link);
if (!$result) {
	 mysql_error();
    die('Could not query:' . mysql_error()); 
}
echo $result;
$num_rows = mysql_num_rows($result);
echo $num_rows;

Re: mySQL query works, but returns false in PHP

Posted: Tue Aug 24, 2010 12:59 pm
by AbraCadaver
What does the echo $num_rows; show?

Re: mySQL query works, but returns false in PHP

Posted: Tue Aug 24, 2010 1:35 pm
by oscardog
Personally I write queries like this, no idea if it will fix your problem though:

Code: Select all

$query =  "SELECT * FROM uidhistory WHERE UID = '1' LIMIT 0, 30"; //No weird wonky single quotes around fieldnames/table names for a start
And then if you include a variable in a query:

Code: Select all

$query =  "SELECT * FROM uidhistory WHERE UID = '".$var."' LIMIT 0, 30";
Give that a go :)

Re: mySQL query works, but returns false in PHP

Posted: Tue Aug 24, 2010 2:04 pm
by McInfo
I trimmed the code to highlight the important lines. See my comments.

Code: Select all

// mysql_connect() returns a MySQL resource
$dbhandle = mysql_connect('localhost', 'root', 'password');

// mysql_select_db() returns a boolean (true or false)
$link = mysql_select_db('exp', $dbhandle);

// $link is not a MySQL resource
$result = mysql_query($query, $link);

Re: mySQL query works, but returns false in PHP

Posted: Tue Aug 24, 2010 2:30 pm
by mikosiko
oscardog wrote:

Code: Select all

$query =  "SELECT * FROM uidhistory WHERE UID = '1' LIMIT 0, 30"; //No weird wonky single quotes around fieldnames/table names for a start
+1 about the " usage
-1 about "//No weird wonky single quotes around fieldnames/table names for a start"

the "weird wonky single quotes" are called "backtikcs" and have an important meaning/usage that could save you a lot of headaches sooner or later (and you know the Murphy's laws already :) ) if you are not very consistent and careful with your choice of table/column names... and even if you are, nobody can prevent that MYSQL new version add more reserved words to the existent ones. :)
http://dev.mysql.com/doc/refman/5.1/en/ ... words.html

I like the "weird wonky single quotes" :wink: