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 purpose of the code snippet provided in the forum thread regarding PDF manipulation in PHP?
- Are there alternative methods or best practices for obtaining host information in PHP to avoid potential errors with gethostbyaddr()?
- How can the max_execution_time setting in PHP be effectively utilized to prevent timeouts in scripts that require extensive processing time?