Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » DB Connection

DB Connection

The following tutorial will teach you how to connect to a database using PHP.

Here is the code to connect to a database

<?php
/* CONNECTION VARIABLES */
$db_hostname = "yourhostname"; // Usually "localhost"
$db_username = "yourusername";
$db_password = "yourpassword";
$db_name = "yourdatabasename";

$conn = mysql_connect($db_hostname, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name, $conn) or die(mysql_error());
?>


$db_hostname = "yourhostname"; // Usually "localhost"

This variable is your site's hostname. Which is usaully "localhost".



$db_username = "yourusername";

The username your host assigned to you, or you picked if you set up your server.



$db_password = "yourpassword";

The password you were provided by your host or the one you picked.



$db_name = "yourdatabasename";

The name of your database.



$conn = mysql_connect($db_hostname, $db_username, $db_password) or die(mysql_error());

"$conn" is the variable that holds all the connection information. "mysql_connect" is a predefined function in PHP that allows you to connect to MySQL. the "or die" part is saying if the connection to SQL fails kill the script and print the error that was encountered. "mysql_error()" prints the specific error.



mysql_select_db($db_name, $conn) or die(mysql_error());

The "mysql_select_db" selects the database that is filled in the "$db_name" variable. The "$conn" variable holds all the connection information that was filled at the beginning of this script. Once again if this part of the script fails it will print why using "mysql_error()".



Now you know how to connect to a database using PHP.

Follow Scriptplayground on Twitter (@scriptplay)

Comments: DB Connection

 mark  Sun Aug 24, 2008 9:59 am  
elow
 Download  Tue Feb 16, 2010 3:52 pm  
that is Cool key connection
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles