如何在MySQL查询中判断无结果并集成提示信息到现有代码?
Hey there! Let's get this sorted out for you. The main issues with your attempted code are mixing up the old mysql extension functions with your current mysqli setup, plus a small syntax error. Here's how to properly integrate the "no results" message into your existing code:
Step 1: Fix the function and logic errors
First, you're using mysql_num_rows() which belongs to the deprecated mysql extension—since your code uses mysqli_query(), you need to use mysqli_num_rows() instead. Also, your conditional syntax was incorrect; we need to first check the number of rows returned before deciding whether to loop through results or show the no-results message.
Step 2: Updated Full Code
Here's your revised code with the no-results message properly integrated, plus an extra check to handle potential query errors:
$result = mysqli_query($con, $sql); // First, check if the query executed successfully if (!$result) { echo "<h3>Oops! There was an error with your query. Please try again later.</h3>"; } else { // Get the number of rows returned $totalRows = mysqli_num_rows($result); if ($totalRows === 0) { // Show no results message when there are no records echo "<h3>There are no result found.</h3>"; } else { // Loop through results as you originally did while ($row = mysqli_fetch_array($result)) { echo '<div class="mydiv">'; if($row['photo']){ echo "<p>" . '<span class="glyphicon" aria-hidden="true"></span>' . "</p>" . "<p>" . "<img src=http://localhost:8888/example/images/" . $row['photo'] . "><hr>"; } else { echo '<p>' . '<span class="glyphicon" aria-hidden="true"></span>' . $row['message'] . '</p>'; } echo '<p>' . '~' . $row['username'] . '</p>'; echo '<p>' . $row['datetime'] . ' ' .'(UTC)' . '</p>'; echo '</div>'; } } }
Key Changes Explained:
- Query Error Check: Added
if (!$result)to catch cases where the SQL query fails (e.g., invalid syntax, missing table), so your users get a meaningful message instead of a blank screen or PHP error. - Correct Row Count Function: Used
mysqli_num_rows($result)to get the number of rows, which matches yourmysqliextension usage. - Clear Conditional Flow: First check if there are no rows—if so, show the message. Otherwise, proceed with your existing loop to display results.
That should do it! Now when your query returns no records, users will see the "no results" message, and everything will work as expected when there are records to show.
内容的提问来源于stack exchange,提问作者user2192094

