Connect to MySQL database using php

Connect to MySQL database using php

Connect to MySQL database using php, this is simple php code for connecting to mysql database using php and then selecting the database. Here i’m using three php functions one is mysql_connect and the other one mysql_select_db, and the next is mysql_error function. First i’ll use mysql_connect() for connecting to database, next mysql_select_db() for selecting database. And mysql_error() will be used for showing any query related error. And die for exiting the script.

First of all i’m using mysql_connect to connect with database, for this you need login credentials

  • Database Host
  • Database User Name
  • Database Password

Then i’m assigning this database connection in a variable, to check connection exists or not? Then if the connection not exists it will exits current script using die function and display’s error in web browser using mysql_error().

Next selecting the database, if the database selection is failed then it will exists the script and output’s error to browser.

[php] <?php $connection = mysql_connect(‘localhost’, ‘root’, ”);
if (!$connection){
die("Database Connection Failed" . mysql_error());
$select_db = mysql_select_db(‘test’);
if (!$select_db){
die("Database Selection Failed" . mysql_error());
Vivek Vengala

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: