Store SQL statement to be executed in a variable
$sql = "Select * from Students";
Execute a query using as stored sql statement in a variable
$result = mysqli_query($conn, $sql);
Get result of a Query by checking if any values were returned using the mysqli_num_rows() function
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
//output code in here.....
echo $row['fieldname'];
}
}
<?php
//store the query into a variable
$sql = "SELECT id, firstname, lastname FROM MyGuests";
//run the query and store the result in a variable
$result = mysqli_query($conn, $sql);
//loop through the result variable and print out its contents if a result was returned
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
//good practice to close the connection at the end of the page
?>
<?php
//store the query into a variable
$sql = "SELECT id, firstname, lastname FROM MyGuests";
//run the query and store the result of the query in a variable called $result
$result = mysqli_query($conn, $sql); //run the query
// print table header and opening table tag
echo "<table><tr><th>ID</th><th>Name</th></tr>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td> </tr>";
}
echo "</table>";
//close connection
mysqli_close($conn);
?>