How to connect to the mysql database in php?

This question is often asked by the new PHP Developer who is trying to learn PHP themselves.

Here’s the syntax:

$conn = mysql_connect(“hostname”, “username”, “password”) or die(mysql_error());
$q = mysql_query(“use databasename”);

Where the “hostname” will be mostly “localhost” if you’re working in local computer. Hosting provider mysql servers also may have “localhost” but some time they have unique server name like “”


Where the “username” and “password” will be “root”  and  ” ” (blank)  if you are in local computer. But it will differ for online Hosting!
Here’s the example code (localhost):

$conn=mysql_connect("localhost","root","") or die(mysql_error());
$q=mysql_query("use play");

Here’s the example code (example hosting provider):

$conn=mysql_connect("localhost","theonly","e3dcg") or die(mysql_error());
$q=mysql_query("use play");

Keep this connection in a separate file so whenever you need you can include this file in your PHP file using below code:


I hope this helped a little bit for a beginner PHP Devloper, Best of LUCK!

About the Author


Software Engineer, Blogger etc., Visit my Youtube channel - <a href="">Click Here</a>

1 thought on “How to connect to the mysql database in php?

Leave a Reply

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