PHP Knowledge Base

Example of a MySQLi Object-oriented SELECT Statement

For cases where results may be zero

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

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

if ($result->num_rows > 0) {
    echo "<table><tr><th>ID</th><th>Name</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?>

When results are known to be greater than zero

$conn = new mysqli($servername, $username, $password, $db__residents);

if ($conn->connect_error) {
	die("Connection failed: " . $conn->connect_error);
}
	
if (isset($_POST['submit__temp_date']))
{	
	$sql = "SELECT * FROM $table__residents WHERE status = 'active'";
	$stmt = $conn->query($sql);
	
	while($row = $stmt->fetch_assoc()) {
		
		$eke_name = $row['eke_name'];

		$html_result = "%s<br>\n";
		echo sprintf($html_result, $eke_name);
	}
}