PHP Includes file for connection

Permabanned
Joined
22 Apr 2007
Posts
1,805
Now, I all know you are being patient with me (most of the time :p) and I have this one simple question to ask (I think).

Some of my web pages appear to have multiple connections to the DB in them.

I have seen some PHP examples which call a file at the start

Code:
<?php
include 'somefile.html';
?>

can I have my connection details in here?

If so, can it be a PHP file?

for example, create a file called connect.php and do this

Code:
<?php
include 'connect.php';

//code
?>

and connect.php has this in it

Code:
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');

Is that how it works?
 
I usually put the mysql connect code in a db_connect() function in a separate file. Then I include the file in my pages and only call db_connect() when I need to use the database.

That way it isn't establishing a connection unless it's going to be used.
 
I am in the middle of creating a database class that handles all database tasks. Nothing spectacular but it just keeps all the DB-related stuff together. Been using PDO too. Tis quite nice though found it a little tricky at first. So used to mysql_query() et al.
 
I currently include \library\config.php and then include \library\opendb.php but i'm struggling to find the right chmod for the library folder. Current I can go to ......serverrenewal\library\ and the directory is listed. At the moment it's set at 755

read through a few pages but still none the wiser, what's the recommended for this folder??
 
place the directory outside of the document root. eg

/library
/www

no one will be able to browse the folder/files that way. you'll need to configure the include_path -easiest way is to use htaccess at the root of your site.

Code:
php_value include_path ".:/full/path/to/library"

now you can include any php file in this folder from any script on your site without having to worry about specifying the full path. a simple

Code:
include 'file.php';

is all you need regardless of folder/file structure.
 
I usually put the mysql connect code in a db_connect() function in a separate file. Then I include the file in my pages and only call db_connect() when I need to use the database.

That way it isn't establishing a connection unless it's going to be used.

This is a good way to keep your code tidy, i use this myself.
 
Back
Top Bottom