Connect PHP to MySQL database

SAMPLE: A FEEDBACK SYSTEM


After setting up the database the next thing is to connect our PHP pages to the database.
PHP primary database is MySQL, so it support several MySQL function, compare to any other RDBM.
PHP function or syntax to connect to MySQL RDBMS is:

mysql_connect (hostname, username, password)

This is often followed by the code that selects your actual database

mysql_select_db (database_name)


Now to connect to our BGdb database, I use the PHP code below, this includes the two functions above, and I supply the right value for the parameters.

$conn = mysql_connect ('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
mysql_select_db ('BGdb') or die ('Could not select database: ' . mysql_error() );


Because we are accessing the site on a local sever; the value for some of these parameters remains the same, such as:
 
Hostname = ‘localhost’ (though most online server most especially Linux/cpanel hosting I’ve used also leave the hostname as localhost, except for windows hosting I’ve use; nevertheless if your hosting company must use another name other that localhost then you will be informed. )

Username = ‘root’ (root is a default MySQL username when you are on a local server, you will however using a more unique or secure name when you are on an internet host)

Password = ‘’ (actually this password parameter is left empty. This is the default password for ‘root’ on a local server, you will however using a more unique and secure password when you are on an internet host)

Database_name = 'BGdb' (the name we gave to the database)

 

To actually use the connection string, programmer or developer prefer putting this important setting into separate file because severally pages will be using it, so that you with have just one file (For example, conn.php) to modify (instead of several pages) when moving the website from a localhost to an internet host.

So create a new page name it conn.php and put the connection string, as we have below.

 

conn.php
<?php
$conn = mysql_connect ('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
mysql_select_db ('BGdb') or die ('Could not select database: ' . mysql_error() );

?>

 

Next »


Return to PHP Sample Main Page