You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP出现A non-numeric value encountered警告,求SQL及代码修正方案

Fixing "Warning: A non-numeric value encountered" in Your PHP Database Code

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:33:31