How To Connect MySQL Using PHP – mysql_connect

The PHP language is widely used in server-side application development along with various add-ons. In server-side application the database connection is necessary to store and retrieve the information during execution.

Here, we describe the simple way to connect MySQL database with your PHP program. You can connect more than one Databases with your PHP program.

Database connection with single database:

No need to create database connector object while making connection with a single database. Refer the below sample code.

<?php
 mysql_connect('database_host',  'database_username',  'database_password') or die('Error: Database server connection failed!');
 mysql_select_db('database_name') or die('Error: Database selection failed!');
 ?>

Where,

database_host – Database host name (e.g localhost)

database_username – Database login username

database_password – Database login password

database_name – Name of the database to be connected

Database connection with more than one database:

Refer the below sample code.

<?php
$db_connector_1 = mysql_connect('database_host_1',  'database_username_1',  'database_password_1') or die('Error: Database 1 server connection failed!');
mysql_select_db('database_name_1',  $db_connector_1) or die('Error: Database 1 selection failed!');

$db_connector_2 = mysql_connect('database_host_2',  'database_username_2',  'database_password_2') or die('Error: Database 2 server connection failed!');
mysql_select_db('database_name_2',  $db_connector_2) or die('Error: Database 2 selection failed!');

$db_connector_3 = mysql_connect('database_host_3',  'database_username_3',  'database_password_3') or die('Error: Database 3 server connection failed!');
mysql_select_db('database_name_3',  $db_connector_3) or die('Error: Database 3 selection failed!');
?>

Where,

database_host – Database host name (e.g localhost)

database_username – Database login username

database_password – Database login password

database_name – Name of the database to be connected

>> Download Source Code

You Might Also Like

Leave a Reply

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