Last Update - 02 Jul 2020

How to connect to MySQL database using PHP

How to connect to MySQL database using PHP

Let's start with PHP and MySQL. The first thing to do is connect to the database MySQL, and try to get information on database tables on the page. The function to connect to MySQL is called mysqli_connect ().

This function returns a connection to pop for the database MySQL connection, that's called a database handling.

There are few important MySQL functions for the PHP MySQL commands:

  • 1. mysqli_connect
  • 2. mysqli_query
  • 3. mysqli_num_rows
  • 4. mysqli_fetch_array
  • 5. mysqli_close

Now Let's start with first function of PHP for creating a connection:

mysqli_connect :

<?php
$username = "yourName";
$password = "yourPassword";
$database = "databaseName";
$hostname = "localhost"; 
//connection to the database
$dbcon = mysqli_connect($hostname, $username, $password, $database) or die("Unable to connect to MySQL");
echo "Connected to MySQL Database";
?>

After connection successfully created need to hit a query where data is stored with table:

Top 50 MySQL Interview Questions and Answers

mysqli_query :

<?php
$query = "SELECT * FROM table_name";
mysqli_query($dbcon, $query) or die('Error in querying database');
?>

When the query is executed we need to how mutch data received on page :

mysqli_num_rows :

<?php
if($row = mysqli_num_rows($result_query)) {
 echo 'Total '. $row . ' record found.';
}
else{
 echo 'No record found';
}
?>

Now we just need to go through all the rows of that query which we need mysqli_fetch_array which stores the rows in an array, we can get the data of this array usning while loop :

mysqli_fetch_array :

<?php
while ($row_data = mysqli_fetch_array($result_query)) {
 echo $row_data['firstName'] . ' ' . $row_data['lastName'] . ': ' . $row_data['emailId'] .'<br />';
}
?>

Finally we need to close the database connection using mysqli_close :

mysqli_colse :

<?php
mysqli_close($dbcon);
?>

Result

<?php
$username = "yourName";
$password = "yourPassword";
$database = "databaseName";
$hostname = "localhost"; 
//connection to the database
$dbcon = mysqli_connect($hostname, $username, $password, $database) or die("Unable to connect to MySQL");
echo "Connected to MySQL Database";
$query = "SELECT * FROM table_name";
mysqli_query($dbcon, $query) or die('Error in querying database');
if($row = mysqli_num_rows($result_query)) {
 echo 'Total '. $row . ' record found.';
 while ($row_data = mysqli_fetch_array($result_query)) {
  echo $row_data['firstName'] . ' ' . $row_data['lastName'] . ': ' . $row_data['emailId'] .'<br />';
 }
}
else{
 echo 'No record found';
}
mysqli_close($dbcon);
?>

More For You

Did you find this page helpful? X