views:

75

answers:

4

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?

+4  A: 

$mysql_connection is unknown inside the function's scope.

If you are using only one connection in your script, you could theoretically also omit the connection specifier:

$result = mysql_query($query);

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

function getTitle() 
 {
   global $mysql_connection;
   .....

 }

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:

Pekka
Hi Pekka.. please check out this thread over here that you might enjoy: http://stackoverflow.com/questions/3415710/php-get-variable-from-function/3415771#3415771
Fosco
@Fosco I added my 2 cents there. Also check out my update to this question here (it took me a while to find the question I wanted to link to.)
Pekka
There are many right answers, but this is was first so I declare this as the right answer.I'm using only one connection so your first suggestion worked.
ne5tebiu
+2  A: 

That would be because you are referencing $mysql_connection which is declared in your config.php and is now out of scope. You can omit that parameter entirely as long as you're only using one connection. Just call mysql_query($query);

Fosco
+1  A: 

Put the following inside your function.

global $mysql_connection;

What has happened is that your $mysql_connection variable isn't in the scope of the function.

I have encountered this same issue before also.

Icode4food
+1  A: 

This is because $mysql_connection variable isn't visible in function body. Use

global $mysql_connection

in the beginning of the function

ivan73