Okay, so I have the weirdest problem right now. My code is fine! It works PERFECTLY as I want and expect it to, which is a major shock to me, because every time I go to do MySQL I get endless problems that I can never find a solution to.
But today, everything works perfectly. So what’s the problem? The problem is that when I try to wrap my code in a function, it just… stops working! I have error checking after every step and it works fine when in it’s own file and lines. But I need to put it in a function so I can add parameters (hence the “extraQuery” variable), and “return” it so that I can access it from a separate file.
Here is my base code:
$link = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect: " . mysql_error());
mysql_select_db($db_name, $link) or die("Couldn't connect to database: " . mysql_error());
$extraQuery = "";
$result = mysql_query("SELECT * FROM things " . $extraQuery . " ORDER BY RAND() LIMIT 1", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
mysql_close($link);
echo($row['content']);
As I said, it works completely fine as that is. But when I do this….
function getResult(){
$link = mysql_connect($db_host, $db_user, $db_pass) or die ("Unable to connect: " . mysql_error());
mysql_select_db($db_name, $link) or die("Couldn't connect to database: " . mysql_error());
$extraQuery = "";
$result = mysql_query("SELECT * FROM things " . $extraQuery . " ORDER BY RAND() LIMIT 1", $link);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
mysql_close($link);
echo($row['content']);
}
getResult();
..It stops working at the second line, telling me “No database selected”. But as you can see, I am explicitly selecting a database that DOES exist and otherwise works when it’s not in a function.
And just to stress this, it is NOT my user permissions, nor is it the name of the database; because it works perfectly when outside of the function.
Any possible aid would be greatly appreciated.
Due to variable scope your database variables are not available inside of the function. You need to pass it as an argument for
getResult()to have access to it: