MySQL SELECT

MySQL SELECT statement is used to fetch data from a database table.

Select Data From a MySql Database table

Syntax:
SELECT column_name(s) FROM table_name
Example:

The following example selects single row data stored in the "contact" table.

<?php
// Create connection
    $con=mysqli_connect("example.com","alex","qwerty","db_name");
    
// Check connection
if (mysqli_connect_errno($con)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

    $query=mysqli_query($con, "SELECT * FROM contact");
    $data = mysqli_fetch_array($query);
    echo $data["name"];
?>

We can also use PHP while() for selecting multiple rows data.

<?php
// Create connection
    $con=mysqli_connect("example.com","alex","qwerty","db_name");
    
// Check connection
if (mysqli_connect_errno($con)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

    $query=mysqli_query($con, "SELECT * FROM contact");
    while($data = mysqli_fetch_array($query)){
        echo $data["name"]."<br>";
    }
?>

Display the results in an HTML table

<?php
// Create connection
    $con=mysqli_connect("example.com","alex","qwerty","db_name");
    
// Check connection
if (mysqli_connect_errno($con)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

    $query=mysqli_query($con, "SELECT * FROM contact");
?>

<table border='1'><tr>
    <th>Firstname</th>
    <th>Lastname</th>
</tr>

<?php while($data = mysqli_fetch_array($query)){ ?>
<tr>
    <td><?php echo $data["name"]; ?></td>
    <td><?php echo $data["email"]; ?></td>
    <td><?php echo $data["message"]; ?></td>
</tr>
<?php } ?>

</table>