How can one handle cases where a specific record does not exist in a database when trying to retrieve data in PHP?
When trying to retrieve data from a database in PHP, it is important to handle cases where a specific record does not exist. One way to handle this is by checking if the query returned any results and then displaying an appropriate message if the record is not found. This can be done using PHP's mysqli_num_rows function to check if there are any rows returned by the query.
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve data
$sql = "SELECT * FROM table WHERE id = $id";
$result = $conn->query($sql);
// Check if record exists
if ($result->num_rows > 0) {
// Record found, fetch data
while($row = $result->fetch_assoc()) {
// Process data
}
} else {
// Record not found
echo "Record not found";
}
// Close connection
$conn->close();