Select Data From a MySQL Database

MySQL SELECT statement is used to select data from one or more tables.

Syntax

MySQL basic syntax for selecting the data from a table :

SELECT column1_name, column2_name FROM table_name;

You can use the * character to select ALL columns from a table.

SELECT * FROM table_name;

Select Data With MySQLi

The following example selects the id, first_name, last_name and email columns from the user table and displays it on the page

Example

<?php

    // Create connection
     $link = mysqli_connect("localhost", "root", "", "demo");
 
    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Attempt select query execution
    $sql = "SELECT * FROM user";
    if($result = mysqli_query($link, $sql)){
        if(mysqli_num_rows($result) > 0){
            echo "<table>";
                echo "<tr>";
                    echo "<th>id</th>";
                    echo "<th>first_name</th>";
                    echo "<th>last_name</th>";
                    echo "<th>email</th>";
                echo "</tr>";
            while($row = mysqli_fetch_array($result)){
                echo "<tr>";
                    echo "<td>" . $row['id'] . "</td>";
                    echo "<td>" . $row['first_name'] . "</td>";
                    echo "<td>" . $row['last_name'] . "</td>";
                    echo "<td>" . $row['email'] . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            // Free result set
            mysqli_free_result($result);
        } else{
            echo "No records matching your query were found.";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

?>