By: Prem Tiwari | Last Updated: | In: Mysql, PHP Tutorial
In this tutorial, I will explain simple and easy steps that will help you to create a database connection with MySql database with PHP applications. It is very easy to write a script in PHP to get connect with most of the popular open source database like MySql.
1 2 |
$conn= mysql_connect("hostname", "username", "password") or die("cannot connect to server"); |
Below is the complete example of how to make a connection with MySql using the PHP code. In the below example change the DB_SERVER, DB_USERNAME, DB_PASSWORD, and DB_DATABASE as per your database credential.
1 2 3 4 5 6 7 8 |
<?php #define the variable names define('DB_SERVER', 'localhost'); //Your hostname define('DB_USERNAME', 'root'); // database username define('DB_PASSWORD', 'test@123'); // database password define('DB_DATABASE', 'testdb'); // database name |
After defining the database variables, use the below code to make a connection with the database.
1 |
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die('Unable to connect'); |
Now use the below code to select your database to use in your PHP based application.
1 2 3 4 5 6 7 8 |
$database = mysql_select_db(DB_DATABASE) or die('Unable to select'); if (!$database) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($database); |
Prem Tiwari is the founder of FreeWebMentor.com and also a professional developer who has vast experience in PHP and open source technologies. Apart from this, he is a blogger by hobby and also he has been a regular speaker of WordPress sessions in various IT Companies. View all posts by Prem Tiwari
Database, How to Connect Database With PHP, mysql database connection, PHP, php database connection