How to connect to MySQL database using PHP

Connecting to MySQL database in php and retrieve information of table into the browser.

How to connect to MySQL database using PHP

Let's start with PHP and MySQ. 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 inportant 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:

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

?>

 

Top