MySQLi – Select Data

The SELECT command allows us to select information from our database and do the following:

– send the data back to the requesting web page.
– display the data directly from the PHP script (we will look at this option).

1
2
3
4
5
6
7
8
9
10
11
12
13
 
$sql = "SELECT * FROM Messages";
$result = $conn->query($sql);
 
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Title: " . $row["title"]. " - Message text: " . $row["messagetext"]. " " . $row["email"]. "<br>";
        // we can access each field through the $row variable.
    }
} else {
    echo "0 results";
}

The above code selects all data from the ‘Messages’ table. However, we can set criteria on the data we want to select.

When using the echo function, you can use any HTML to style your output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
$sql = "SELECT title, messagtext FROM Messages WHERE email = 'smith@smith.com'";
$result = $conn->query($sql);
 
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Title: " . $row["title"]. " - Message Text: " . $row["messagetext"]. "<br>";
        // we can access each field through the $row variable.
        // the '.' allows us to concatenate the fields.
    }
} else {
    echo "0 results";
}