0

Forgive me but I am very new to PHP and SQL.

I am simply trying to assign the results of an SQL query to a PHP variable ($num). The SQL query is counting how many times customer_id appears in a table. However when i use the code below i get the error :

Warning: mysql_result() expects parameter 1 to be resource, boolean given in ... line **

session_start(); is at the top of the page and {$_SESSION['userid']} is actually an integer value of the currently logged in user which corresponds to the customer_id in the bookings table. Database connection is the include/db_connection.php (which i know works). The code i am using currently is :

    <?php
    include 'include/db_connection.php'
    $num = mysql_result(mysql_query("SELECT COUNT(*) FROM bookings WHERE customer_id={$_SESSION['userid']}"),0);
    ?>
  • 1
    **NEVER** chain database calls like that. If anything fails, you end up in the exact situation you're in - things blew up, and no way to tell what blew up. – Marc B Jan 27 '14 at 17:39

2 Answers2

0

The fact that a boolean is given suggests that the query failed, and the mysql_query returned FALSE. You could try to use mysql_query("foo") or die(mysql_error()); to find out what's wrong.

Martin149
  • 23
  • 4
0

You need to tell php to fetch the row - mysql_query() simply returns a boolean (true/false) result. Store the query result in a variable and fetch the result with $row = mysql_fetch_assoc($myqueryresult) or $row = mysql_fetch_array($muqueryresult) and use the field result from $row['column'] where needed.

It might be easier to use the count rows function in php rather than COUNT in sql too.

Ideally you should use the mysqli api to query mysql instead as it is much more secure and modern.

Alan Kael Ball
  • 680
  • 6
  • 17