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:

<?php
$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 “sql.hosting.etc”

 

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):

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

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

<?php
$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:

include(“connection.php”);

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

One Comment

Add a Comment

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