Select Data From a Database Table Using PHP MySQLi

In previous tutorial we have seen how to Insert Data into Database using PHP MySQLi and we understand how to add records in mysql database table using PHP.

In this tutorial we will discuss how to select data from database table using PHP MySQLi. This post will let you help to understand how to fetch data from database table using PHP MySQLi.

In this example we select all records from database table using SELECT * FROM `tablename`.

SELECT statement is used to get records from database tables. * is used to get all records from table. We can also get specific column records from database table using columname instead of *.


To Get all records

SELECT * FROM `tablename`

To Get specific column records

SELECT `columname1`,`columname2` FROM `tablename`

In previous tutorial i have created table `tbl_users` and retrieving records from same table in this tutorial.

Read

Insert Data into Database using PHP MySQLi

How to use mysqli_connect in PHP

Database/Table

Database   :  demodb

Table         :  tbl_users

MySQLi Procedural Example

<?php
$db_server ="localhost";
$db_user = "root";
$db_pass = "";
$db_name ="demodb";

// Create connection
$conn = mysqli_connect($db_server, $db_user, $db_pass, $db_name);

// Check connection
if ($conn === false) {
    die("Could not connect::" . mysqli_connect_error());
}

$sql = "SELECT * FROM tbl_users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_array($result)) {

        echo "ID    : " . $row['userID'] . " Name :" . $row['userName'] . " Email : " . $row['userEmail'] . "<br>";
    }
} else {
    echo "No record exists!!";
}

mysqli_close($conn);
?>

MySQLi Object Oriented Example

<?php
$db_server ="localhost";
$db_user = "root";
$db_pass = "";
$db_name ="demodb";

// Create connection
$conn = new mysqli($db_server, $db_user, $db_pass, $db_name);

//check connection
if($conn-> connect_error)
{
	die("Could not connect:". $conn->connect_error);
}

$sql = "SELECT * FROM tbl_users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_array()) {

        echo "ID    : " . $row['userID'] . " Name :" . $row['userName'] . " Email : " . $row['userEmail'] . "<br>";
    }
} else {
    echo "No record exists!!";
}

$conn->close();
?>

Finally you learned about how to fetch data from database in php using mysqli. If you have any query feel free to ask me.

Leave a Comment