PHP – Connecting to MYSQL and Selecting Database

Below is the simple php code that is required to connect to mysql database and select the database you want to work with.

<?php

//Database Server Details
$username = “enter your username”;
$password = “enter your password”;
$dbname = “enter database name”;
$hostname = “enter your hostname”;

//Connecting to Database
$dbc = mysql_connect($hostname, $username, $password)
or die(“Unable to connect to MySQL database, make sure your hostname, username and password are correct!”.mysql_error());
echo “Connection to Database Successful!<br/>”;

//Selecting a Database
$db_select = mysql_select_db($dbname,$dbc)
or die(“Unable to select the database “.mysql_error().”<br/>”);
echo “Successfully Selected the Database!<br/>”;

?>

You can aslo download the code from the link below
Click Here to Download

To check whether you have connected to the database server and selected the database to work with. Firstly, download the file from the above download link, then upload that mysql_connect.php file to your server and view it in your browser. If everything goes ok, you will see these two messages on the screen.

Connection to Database Successful!
Successfully Selected the Database!

Now you can use this file in your php projects, remember to comment these lines with //like this.
//echo “Connection to Database Successful!”;
//echo “Successfully Selected the Database!”;

These echo statements were used for debugging purpose in this script.

Published in PHP Programming

Leave a Comment

  • Allayna's Comment Allayna Posted On: Dec 8th, 2011 at 8:28 pm

    Never would have thunk I would find this so iindpsnesable.

Share This Post

Search »

Recent Comments »

Idalia's Comment
Idalia: It was dark when I woke. This is a more...
Chris's Comment
Chris: This website makes thigns hella eas more...
Allayna's Comment
Allayna: Never would have thunk I would find more...
angie's Comment
angie: Lovely just what I was searching fo more...
phoenix's Comment
phoenix: It’s good page, I was looking for s more...
"Learn Tips & Tricks about Search Engine Optimization, Marketing, Usability, Web Design, PPC and Link Building."