jadedknight Posted May 19, 2008 Share Posted May 19, 2008 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. Link to comment https://forums.phpfreaks.com/topic/106276-solved-how-to-access-database-anywhere-in-app/ Share on other sites More sharing options...
bilis_money Posted May 19, 2008 Share Posted May 19, 2008 include 'db.php'; Link to comment https://forums.phpfreaks.com/topic/106276-solved-how-to-access-database-anywhere-in-app/#findComment-544665 Share on other sites More sharing options...
jadedknight Posted May 19, 2008 Author Share Posted May 19, 2008 include 'db.php'; Is that not the same as require? Link to comment https://forums.phpfreaks.com/topic/106276-solved-how-to-access-database-anywhere-in-app/#findComment-544668 Share on other sites More sharing options...
jadedknight Posted May 19, 2008 Author Share Posted May 19, 2008 Well, I did try include, same result. Read the PHP manual, the functions are nearly the same. Any ideas anyone? Link to comment https://forums.phpfreaks.com/topic/106276-solved-how-to-access-database-anywhere-in-app/#findComment-545043 Share on other sites More sharing options...
corbin Posted May 19, 2008 Share Posted May 19, 2008 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). Link to comment https://forums.phpfreaks.com/topic/106276-solved-how-to-access-database-anywhere-in-app/#findComment-545066 Share on other sites More sharing options...
jadedknight Posted May 19, 2008 Author Share Posted May 19, 2008 Ok I was able to get it to work by including the db into my main index page. But now I get this error when retrieving a row: Resource id #5 Link to comment https://forums.phpfreaks.com/topic/106276-solved-how-to-access-database-anywhere-in-app/#findComment-545070 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.