How can the code snippet provided be modified to display a custom message like "Not found" when a database record is not present?
To display a custom message like "Not found" when a database record is not present, we can modify the code to check if the query returns any rows and display the custom message if no rows are found. We can use the `rowCount()` function to check the number of rows returned by the query and then display the custom message accordingly.
<?php
// Execute the query
$stmt = $pdo->prepare("SELECT * FROM table WHERE id = :id");
$stmt->execute(['id' => $id]);
// Check if any rows are returned
if ($stmt->rowCount() > 0) {
// Display the results
while ($row = $stmt->fetch()) {
// Display the record
}
} else {
// Display custom message
echo "Not found";
}
?>
Keywords
Related Questions
- What is the significance of using "$file_array[$key-1];" in PHP and how can you ensure it outputs the correct sorted entry?
- What is the best practice for appending data to the beginning of a text file in PHP?
- How can the DRY (Don't Repeat Yourself) principle be applied to improve the efficiency of PHP code?