tags:

views:

80

answers:

8

What's wrong with my code? I keep getting this error: Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in functions.php on line 4 error reading database

function gameTableCheck($gn) 

{

    $result = mysql_query("SHOW TABLES LIKE '$gn'",$db) or die ('error reading database'); //This is line 4
    if (mysql_num_rows ($result)>0) {
        return true;
    } else {
        return false;
    }
}

if( gameTableCheck($page) === false ) {
        echo "MAO";
        die();
    }
+3  A: 

$db is not a local variable inside function gameTableCheck, you need to add a global $db; statement at the top of the function.

Wim
or (better IMO) pass in $db as a parameter to the function
fvu
This is assuming of course that there is a `$db` in the global scope.
Ben James
I forgot that, heh, silly me!
Doug
+1  A: 

Well I'd say that $db is not initialized correctly. What you want to do is to use mysql_select_db as such :

<?php
$host = "localhost"; //database location
$user = "user"; //database username
$pass = "pass"; //database password
$db_name = "thename"; //database name

//database connection
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db_name);

//sets encoding to utf8
mysql_query("SET NAMES utf8");
?>

(snippet via)

If you do need to have a specified database variable on each query for some reason, try looking if :

  • the $db variable is set properly

  • the $db variable is within the scope of your function. Consider making it global if needed or passing it to the function as an argument

marcgg
A: 

Is $db a valid MySQL connection?

Paolo
+1  A: 

I assume that $db is not a valid database connection. Did you connect to the database beforehand? Is $db available in that function's scope at all?

You can make it have global scope by using global $db before calling the function.

BastiBense
+4  A: 

The problem is here: mysql_query("SHOW TABLES LIKE '$gn'",$db)

There is no $db in scope.

If you are only using one database connection and you have already connected, you can just remove this argument.

Ben James
A: 

You forgot to open the connection to your database ($db in your code) and select a database before executing a query on it. The error says that the $db variable in your code is not a valid resource and thus it is not defined.

See: http://php.net/manual/en/function.mysql-query.php and http://www.php.net/manual/en/function.mysql-connect.php

TheGrandWazoo
A: 

to find the error you can try putting mysql_error()

$result = mysql_query("SHOW TABLES LIKE '$gn'",$db) or exit( mysql_error() );
ghostdog74
A: 

The gameTableCheck() function has no clue what the $db variable is. Since PHP has no dynamic scoping you have to either declare the variable as global inside the function (if it is a global variable), or pass it as a parameter in the function call.

kemp