How To Connect PHP to Mysql

By September 28, 2016 No Comments

If you want to connect php to mysql, then you are at the right place here I am going to show you how to connect php to mysql. Also I will show you how to connect php to mysql database. Both are different. First we will connect php to mysql by using its hostname, username and password. Then we will connect our connect php to mysql database by the name of the database.

Make a MySql database and user :


If you are using XAMPP or any similar type of applications to create a local server. Then open your browser..

Go to http://localhost/phpmyadmin/

At the top of the left sidebar you will find an option called new. Click it then it will redirect you to a form where you can create a database.

After creating database you have to create an user. For doing this click on the created database. On the top bar there is a option called Privileges . Go there and create a new user.

Connect PHP to MySql:

For connecting php to mysql server you will need 4 strings. Those are:

  1. Host Name
  2. Mysql Username
  3. Mysql Password
  4. Database Name

Now it’s time to connect php to mysql,

    or die("Unable To Connect To My SQL");

To connect php to mysql as i said before @mysql_connect will require 3 strings and those are host,username,password. If those informations are correct then you will be successfully connected to the database. Otherwise the code will die with a message “Unable To Connect To My SQL”. You can change the die message with anything you want.

Again, It’s time to connect to mysql database in php after connecting to the database,

    or die("Unable To Connect To The Database");


@mysql_select_db is used to connect to the database. If any informations are incorrect then it will die a message.

If all the informations are correct you will be successfully connected to mysql database.

It’s super easy, Isn’t it?

Facing any error? Comment Quick….




I am a Web and Mobile Developer. I am also Interested In Blogging.