求助:排查代码中mysqli_num_rows函数及相关SQL查询问题
mysqli_num_rows() Hey there! It sounds like you're tangled up in code chaos after making a bunch of changes, and suspect mysqli_num_rows() might be part of the problem. Let's walk through the most common pitfalls with this function that could be tripping you up:
Calling it on a failed query result
If your SQL query fails (e.g., syntax error, invalid table name),mysqli_query()returnsfalseinstead of a valid result set. Trying to passfalsetomysqli_num_rows()will throw an error. Always validate your query first:$result = mysqli_query($conn, $your_sql); if (!$result) { // Debug the actual SQL error to fix the root issue die("Query failed: " . mysqli_error($conn)); } $row_count = mysqli_num_rows($result);Using it with non-SELECT queries
mysqli_num_rows()only works with queries that return a result set—likeSELECT,SHOW, orDESCRIBE. If you're runningINSERT,UPDATE, orDELETE, you need to usemysqli_affected_rows()instead to get the number of rows changed. Mixing these up is a super common mistake!Forgetting to store results with prepared statements
If you're using mysqli prepared statements, you can't callmysqli_stmt_num_rows()right after executing the statement. You first need to fetch the result from the server to your local script withmysqli_stmt_store_result():$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE email = ?"); mysqli_stmt_bind_param($stmt, "s", $user_email); mysqli_stmt_execute($stmt); // Critical step—store the result before checking row count mysqli_stmt_store_result($stmt); $row_count = mysqli_stmt_num_rows($stmt);Skip this step, and you'll almost always get
0even if there are matching rows in the database.Result set/connection was closed early
If you accidentally close your database connection (mysqli_close($conn)) or free the result set (mysqli_free_result($result)) before callingmysqli_num_rows(), the function won't have access to the data it needs to count rows. Double-check the order of your code to make sure this isn't happening.Your SQL query actually returns no rows
Sometimes the issue isn't the function at all—it's your query! If yourWHEREclause is too restrictive, or there's no data matching your conditions,mysqli_num_rows()will correctly return0. Test your raw SQL query directly in a database tool (like phpMyAdmin or MySQL CLI) to confirm if it returns the rows you expect.
If you can share a snippet of your actual code, we can pinpoint the exact issue even faster.
内容的提问来源于stack exchange,提问作者Prasad Supare

