Header Ads

Select Data From a MySQL Database

The SELECT statement is used to select data from one or more tables:





SELECT column_name(s) FROM table_name
or we 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, name and lastname columns from the Student table and displays it on the page:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "data";

// Create connection$conn = new mysqli($servername, $username, $password, $dbname);
// Check connectionif ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);


$sql = "SELECT id, name, lastname FROM Student";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["lastname"]. "<br>";
    }
else {
    echo "0 results";
}
$conn->close();
?>

Output:


id: 1 - Name: Ankit Bhardwaj
id: 2 - Name: Ashish Rajput
id: 3 - Name: Rahul Paswan


First, we set up an SQL query that selects the id, name and lastname columns from the Student table. The next line of code runs the query and puts the resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, name and lastname columns.


No comments

Powered by Blogger.