PHP and MySQL Connectivity

We know that there are lots of tutorials (some official too) on the internet about PHP and MySQL connectivity. Then why am i posting it here ? i am posting because most of those articles are not simple and easy to understand and this is why we are doing it here. We assume that you have already installed XAMPP in your System and running it using XAMPP control panel.

To connect PHP to MySQL database you need to know following important things:

  1. Host name.
  2. MySQL user name.
  3. MySQL password.

If you have installed XAMPP in your system (not web server) then host name is localhost. By default MySQL user name and password is “root” and blank ( “” ) respectively. Let us create one simple project and try to connect our PHP code to MySQL.

If you are on Windows then there is “htdocs” folder in “C:/xampp/htdocs/” (if installed on default location). If you are on Linux (most probably Ubuntu) then it is located on “/opt/lampp/htdocs” (you should switch to root user before creating folder in it.).

In any case create any folder, lets say “test-db-connection” and create simple PHP file with following code.

$host="localhost";
$user="root";
$password="";
$con=mysql_connect($host,$user,$password);
if(!$con) {
  echo '<h1>Connected to MySQL</h1>';
} else {
   echo '<h1>MySQL Server is not connected</h1>';
}

Save it in the project folder and go to localhost/test-db-connection/filename.php and see what it is giving.

mysql_connect() is PHP inbuilt function to connect to MySQL database with the parameter shown above.

To perform SQL queries, you need to select database. You can do that using mysql_select_db(“database_name”,optional connection variable). Once Database is selected you can perform queries using mysql_query(“SQL query”). Here is sample code.

$host="localhost";
$user="root";
$password="";
$con=mysql_connect($host,$user,$password);
if(!$con) {
  echo '<h1>Connected to MySQL</h1>';
  //if connected then Select Database.
  $db=mysql_select_db("YOUR_DATABASE_NAME",$con);
  $query=mysql_query("YOUR_MYSQL_QUERY",$db);
}
else {
  echo '<h1>MySQL Server is not connected</h1>';
}

I hope you have understood the concept. You can ask any doubt in comment.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126