MySQL Connection Using PHP Script

PHP provides mysql_connect() function to open a database connection. This function takes three parameters and returns a MySQL link identifier on success or FALSE on failure.


Optional − The host name running the database server. If not specified, then the default value will be localhost:3306.

Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process.

Optional − The password of the user accessing the database. If not specified, then the default will be an empty password.

We can disconnect from the MySQL database anytime using another PHP function mysql_close(). This function takes a single parameter, which is a connection returned by the mysql_connect() function.

mysql_close ( $conn );

If a resource is not specified, then the last opened database is closed. This function returns true if it closes the connection successfully otherwise it returns false.

Example to connect to a MySQL server −

<title>Connecting MySQL Server with PHP Script</title>
$dbhost = ‘localhost:8080’;
$dbuser = ‘sainidaya’;
$dbpass = ‘sainidaya123’;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die(‘Could not connect: ‘ . mysql_error());
echo ‘Connected successfully’;
Connecting MySQL Server with PHP Script

All going well, you should see “Connected to MySQL” when you run this script. If you can’t connect to the server, make sure your password, username and hostname are correct.

Once you’ve connected, you’re going to want to select a database to work with. Let’s assume the database is called ‘databasename‘. To start working in this database, you’ll need the mysql_select_db() function:


Now that you’re connected, let’s try and run some queries. The function used to perform queries is named – mysql_query(). The function returns a resource that contains the results of the query, called the result set. To examine the result we’re going to use the mysql_fetch_array function, which returns the results row by row. In the case of a query that doesn’t return results, the resource that the function returns is simply a value true or false.

//execute the SQL query and return records
$result = mysql_query(“SELECT id, class, grade FROM users”);
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo “ID:”.$row{‘id’}.” Name:”.$row{‘class’}.”

I, Dayanand Saini,the founder and chief editor of,have been working as a software engineer from last 4+ years. It's my hobby to learn new things and implement on live environment.

Leave a Reply

Your email address will not be published. Required fields are marked *

42 − 35 =

%d bloggers like this: