// phpShack / PHP & MySQL Tutorials / Connect to MySQL Database
 

Navigation





 

Connect to MySQL Database

The purpose of this tutorial is to show you how to connect to a MySQL database using PHP.



PHP Code Example:
<?
// database.php

// First we will set our variables
$db_host "localhost"// Location of databse usually localhost
$db_user "dateuser"// Username for database
$db_pass "datepass"// Password for user
$db_name "date_test"// Name of our database

// Make our database connection
mysql_connect($db_host$db_user$db_pass// Make connection to database
      
or die("Database not working properly"); // Return error if connect failed
mysql_select_db($db_name// Select our database
      
or die("Could not select database"); // Return error in selection failed

// Now you are connected to the database and we can use select or insert statements etc. 
?>


Its usually best in my opinion to keep sensitive database information in another file besides the one that is actually doing the quieries. Try something like this:
PHP Code Example:
<?
// db_connection.php

$dbhost "localhost";
$dbuser "username";
$dbpassword "password";

function 
dbConnect($db="") {
    global 
$dbhost$dbuser$dbpassword;
    
$dbcnx = @mysql_connect($dbhost$dbuser$dbpassword)
        or die(
"Database not working properly");
    if (
$db!="" and !@mysql_select_db($db))
        die(
"Database unavailable");
return 
$dbcnx;
}

?>


Now when you are creating another php file you don't have to connect to the database again, you just include db_connection.php in your file like so:

include "database_connection.php";

Then you can use the function we created in db_connection.php to connect to whatever database you need. You would do this like so:

dbConnect("database_name");