I have problem with this code show mi error Warning: mysql_result() expects parameter 1 to be resource, boolean given in C:\wamp\www\blogcode\resources\func\blog.php on line 34

function category_exists($name){
        $name = mysql_real_escape_string($name);
        $query = mysql_query("SELECT COUNT(1) FROM 'categories' WHERE 'name'= '{$name}'");
        return (mysql_result($query, 0)=='0') ? false:true;

    }

How to fix this problem?

$query = mysql_query("SELECT COUNT(1) FROM `categories` WHERE `name` = '{$name}'") or die(mysql_error());

Table names and column names must not be surrounded by single quotes, but by backticks.

Table names and column names must not be surrounded by single quotes, but by backticks.

Backticks are really unnecessary unless you are using reserved words as labels. Fact is, they're a MySQL construct and not defined by the ANSI SQL standard. Using the backticks will limit you strictly to MySQL; should you ever port to Postgres, for example, you will need to rewrite every single query.

That may not be a big deal, if you're confident you'll never move off the MySQL platform. But backticks are also a vector for bad practices: using reserved words and being allowed to do so. It's a poor practice, and one that will result in problems the moment a backtick is forgotten. Better to just forgo them all together, in my opinion.

But backticks are also a vector for bad practices

The user is the problem, not the backticks. I'd worry more about SQL injection in the above code then about backticks, and the fact that the mysql extension is deprecated ;)

The user is the problem, not the backticks. I'd worry more about SQL injection in the above code then about backticks, and the fact that the mysql extension is deprecated ;)

You'll hear no disagreement from me on those points. I suppose I have a bit of a pet peeve in regards to backticks. I often wonder if they would've become so widly used if phpMyAdmin didn't include them in its SQL output.

Member Avatar for iamthwee

I'd worry more about SQL injection in the above code then about backticks, and the fact that the mysql extension is deprecated ;)

Prit can you further explain this as I am curious. Since the OP uses my_sql_real_escape with the deprecated version of mysql() isn't it still safe though.

Couldn't agree more about backticks Bob. I only had one time when I came unstuck using them, and that was when I accidentally call a field 'desc' for description, desc being a reserve word.

You would believe how long I took to debug.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.