All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Fetch Data From Database In PHP

Last Updated : Jul 1, 2023

Fetch Data From Database In PHP

In this article we will show you the solution of fetch data from database in PHP, a database operation is an essential part of PHP CRUD functionality (Create, Read, Update and Delete).

It is important to know about each of the three databases separately in order to figure out what each does. MySQL databases and tables can be accessed using PHP APIs.

As long as developers are aware that MySQL cannot be used with PHP 7 or its newer versions, there is no restriction on which database type they can use for their projects.

The only difference between MySQLi and PDO is that PDO is compatible with 12 different database systems, while MySQLi is only compatible with MySQL.

Connecting to the database and running queries: Following the connection, we need to run queries to get data.

Data will be fetched from the database using only select queries in reading operations.

Step By Step Guide On Fetch Data From Database In PHP :-

<?php
  $servername = "localhost";
  $username = "root";
  $password = "";
  $databasename = "TalkersCode";
  // CREATE A CONNECTION
  $conn = new mysqli($servername,
    $username, $password, $databasename);
  // GET CONNECTION ERRORS
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }
  // SQL QUERY
  $query = "SELECT * FROM Student Details;";
  // FETCHING DATA FROM DATABASE
  $result = $conn->query($query);
    if ($result->num_rows > 0)
    {
        // OUTPUT DATA OF EACH ROW
        while($row = $result->fetch_assoc())
        {
            echo "Roll No: " .
                $row["Roll_No"]. " - Name: " .
                $row["Name"]. " | City: " .
                $row["City"]. " | Age: " .
                $row["Age"]. "<br>";
        }
    }
    else {
        echo "0 results";
    }
   $conn->close();
?>
  1. The short tags start with "<?" and end with "?>".
  2. Then we use the connect () / mysqli_connect () function opens a new connection to the MySQL server.
  3. then we used to execute an SQL SELECT statement and save the result in a scoped variable.
  4. In the following step, one or more strings will be output using the echo function.
  5. Then, associative arrays are returned from Fetches by returning one row of data.

Conclusion :-

SQL SELECT statements can be executed through PHP function mysql_query to fetch data from MySQL tables. MySQL data can be fetched in several ways.

There are several options for MySQL_fetch_array ().

I hope this article on fetch data from database in PHP helps you and the steps and method mentioned above are easy to follow and implement.