PHP出现A non-numeric value encountered警告,求SQL及代码修正方案
Hey there, let's break down what's causing this warning and get your code working properly.
The Root Cause
You're using the + operator to build your SQL query string—but in PHP, + is for arithmetic addition, not string concatenation. When you try to add a string (your SQL query fragment) to a number (the result of intval($article_id)), PHP tries to convert the string to a numeric value. Since your SQL string starts with non-numeric characters, it gets converted to 0, and you end up with 0 + 2 = 2 as your "SQL query"—which is obviously invalid, hence the warning.
Quick Fix: Use the Correct String Concatenation Operator
Replace the + with . (PHP's string concatenation operator):
include("database_connection_information.php"); $article_id = 2; $sql = "SELECT article_title, article_text FROM Articles WHERE article_id = " . intval($article_id); $result = $conn->query($sql);
Better Fix: Use Prepared Statements (Avoid SQL Injection!)
While the above fixes the warning, directly concatenating values into SQL queries is risky if $article_id ever comes from user input (like a URL parameter or form submission). Prepared statements are safer and more reliable:
include("database_connection_information.php"); $article_id = 2; // Prepare the query with a placeholder $sql = "SELECT article_title, article_text FROM Articles WHERE article_id = ?"; $stmt = $conn->prepare($sql); // Bind the integer value to the placeholder ("i" = integer type) $stmt->bind_param("i", $article_id); // Execute and get results $stmt->execute(); $result = $stmt->get_result(); // Fetch the article record $article = $result->fetch_assoc();
This approach separates your SQL logic from your data, eliminating SQL injection risks and avoiding manual value formatting.
内容的提问来源于stack exchange,提问作者Stephen Roberts

