学校项目网站Newsletter功能出现mysqli_num_rows参数错误求助
Hey Alexander! Let's break down why you're hitting that warning and fix it up step by step.
First, let's recap the error you're seeing:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given in /customers/4/8/8/web-line.dk/httpd.www/TACO/forside.php on line 19
This message tells us that when you called mysqli_num_rows($sql), the $sql variable wasn't a valid mysqli_result object (it was actually returning false instead). Here's the root cause and fixes:
1. Fix the SQL Syntax Mistake
Look at your SELECT query line:
$sql=mysqli_query($mysqli,"SELECT*FROM newsletter WHERE email='$email'");
You're missing a space between SELECT and *! Databases can't parse SELECT* correctly—this causes the query to fail, so mysqli_query() returns false instead of a result set. Passing that false value to mysqli_num_rows() triggers the error you're seeing.
Fix the syntax by adding the missing space:
$sql=mysqli_query($mysqli,"SELECT * FROM newsletter WHERE email='$email'");
2. Add Error Checking for Your Query
Even with the syntax fixed, it's smart to verify the query succeeded before using the result. Add this right after your query line to catch other potential issues (like misspelled table/column names):
if (!$sql) { die("Query failed: " . mysqli_error($mysqli)); }
3. Critical: Protect Against SQL Injection
Right now, you're directly inserting user input ($email) into your SQL query—this is a major security risk (SQL injection attacks can exploit this flaw). Let's rewrite your code using prepared statements, the safe industry standard for handling user input:
<?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $email = ""; if (isset($_POST['signup-button'])){ include_once "Connect_db.php"; $email = $_POST['signup-email']; if(empty($email)){ echo "Udfyld email"; } else { // Check if email already exists using prepared statement $check_stmt = $mysqli->prepare("SELECT email FROM newsletter WHERE email = ?"); $check_stmt->bind_param("s", $email); // "s" indicates we're passing a string $check_stmt->execute(); $check_stmt->store_result(); // Required to access num_rows if ($check_stmt->num_rows > 0){ echo "Email allerede i system!"; } else { // Insert new email using prepared statement $insert_stmt = $mysqli->prepare("INSERT INTO newsletter (email, dateTime) VALUES (?, NOW())"); $insert_stmt->bind_param("s", $email); if ($insert_stmt->execute()) { // Optional: Add a success message here, e.g. echo "Tak for din tilmelding!"; } else { die("Insert failed: " . $insert_stmt->error); } $insert_stmt->close(); } $check_stmt->close(); } } ?>
Prepared statements automatically handle escaping user input, so you don't have to worry about malicious input breaking your query or compromising your database.
内容的提问来源于stack exchange,提问作者Alexander Schneider

