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();
}
$db is not a local variable inside function gameTableCheck, you need to add a global $db; statement at the top of the function.
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.
Well I'd say that $db is not initialized correctly. What you want to do is to use mysql_select_db as such :
$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
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.
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.
to find the error you can try putting mysql_error()
$result = mysql_query("SHOW TABLES LIKE '$gn'",$db) or exit( mysql_error() );
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.
来源:https://stackoverflow.com/questions/2005720/warning-mysql-query-supplied-argument-is-not-a-valid-mysql-link-why