For example:
<?
function getTitle(){
$query="SELECT title FROM news WHERE author = 'admin' LIMIT 5";
$result = mysql_query($query, $mysql_connection);
$data = mysql_fetch_array($result,MYSQL_ASSOC);
return $data['title'];
}
?>
And every time I want to submit a MySql query I must always include config.php inside the function, otherwise it does not work.
I tried including at the beginning of the file but still no result.
Config.php file consists of connection to the database and selection of the database. No errors there.
What seems to be the problem?
$mysql_connectionis unknown inside the function’s scope.If you are using only one connection in your script, you could theoretically also omit the connection specifier:
That way, your mySQL calls would work without any additional steps.
If you want to keep the identifier (you should if you have multiple connections open), as a quick fix, you can use
to import the connection into the function’s scope.
An advanced (and somewhat cleaner) way is to have a Singleton or static object containing the database connection. See this question for good examples: