Jump to content

[SOLVED] How to Access Database Anywhere in App


jadedknight

Recommended Posts

Hey, I am trying to get better at PHP by building myself a CMS but I am stuck. I am programming functionally, I know there are OOP solutions, and solutions that involve libraries such as PEAR but I am not interested in those.

 

Basically, how am I able to access a database connection anywhere in my application, for example in a function. This is my current code:

<?php require('db.php');
function preferences() {
	$query = "SELECT * FROM preferences WHERE id = 1";
	$result = mysql_query($query) or die('Query failed: ' . mysql_error());
	echo $result;
}
?>

 

I have included the database connection information but it does not connect, I am guessing due to variable scope. How do I get around this without creating a new connection inside every function.

When an SQL connection is not specified in a MySQL function call, the open connection is assumed.  Therefore, if you have a connection open before you call the mysql_query function, it will automatically find it.  So, I don't think it's a variable scope problem.

 

Can you post the code from db.php (remove the user/pass if you want).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.