This program connects to a database, runs a SELECT query to get all users, and prints their id and name. It shows how to use the query method and handle results.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Run a SELECT query
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["name"] . "\n";
}
} else {
echo "0 results\n";
}
$conn->close();
?>