Robin Van den Broeck
Robin Van den Broeck

Reputation: 1678

PHP: mysql query gives a boolean

<?php
class Page {
    function getPage($urlOfPage){
        $result = mysql_query('SELECT category, title FROM rs-planet WHERE url = "'.  mysql_real_escape_string($urlOfPage));
        if(mysql_num_rows($result) === 0){
            header('HTTP/1.0 404 Not Found');
            exit;
        }
        else{
            return $page[] = mysql_fetch_array($result);
        }
    }
}

?>

And I have this errors:

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\rs-planet\classes\page.php on line 6

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\rs-planet\classes\page.php on line 11 And I don't see the problem...

And if I do var_dump @ $result I get a boolean. (If it's founded @ the db it gives true, if it isn't it gives me false.)

PS. Sorry for my bad English, my main language is Dutch.

EDIT: var_dump(mysql_error) =

string(152) "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"index' at line 1"

Upvotes: 0

Views: 4322

Answers (3)

kitti
kitti

Reputation: 14814

mysql_query returns false if the query cannot be executed (i.e. bad syntax). Try surrounding rs-planet with backticks:

$result = mysql_query('SELECT category, title FROM `rs-planet` WHERE url = "'.  mysql_real_escape_string($urlOfPage) . '"');

I'm thinking the - in the table name is screwing up the syntax.

EDIT: Also, PDO makes it much easier to debug these issues since you don't need to use mysql_error() to get the error message - it's included in the Exception thrown by PDO. http://php.net/manual/en/book.pdo.php

SECOND EDIT: Actually the problem is likely the missing quote. Fixed my code, but see the other answers...

Upvotes: 2

dotancohen
dotancohen

Reputation: 31481

mysql_query returns FALSE on error. Your error is that you are not closing the quote in your query. Try this:

        $result = mysql_query('SELECT category, title FROM rs-planet WHERE url = "'.  mysql_real_escape_string($urlOfPage).'"');

Upvotes: 1

Andrew Leach
Andrew Leach

Reputation: 12973

mysql_query returns false on an error.

You have WHERE url=" but no closing quote after the url string.

Upvotes: 1

Related Questions