为何PHP判定我的SQL UPDATE查询代码执行失败?
你的SQL UPDATE查询问题分析与修复方案
先看你提供的错误输出里的SQL语句,一眼就能发现几个核心问题:大部分字段的赋值是空的,字符串类型的值没加引号,而且你的写法还存在严重的安全风险。咱们逐个解决:
1. 变量未赋值导致的语法错误
错误返回的SQL里,除了source=Tom和ID=18,其他字段都是字段名=的格式——这说明你的$namerecipe、$ingredient1等变量根本没获取到值,是空的。SQL不允许给字段赋值空表达式,这直接触发了语法错误。
你需要先排查变量来源:
- 如果是表单提交,检查表单字段的
name属性和PHP变量名是否完全匹配(比如<input name="namerecipe">对应$namerecipe = $_POST['namerecipe'];) - 在执行SQL前,用
var_dump($namerecipe, $ingredient1, $ingredient2, ...);打印所有变量,确认它们是否有正确内容。
2. 字符串字段未加引号的语法问题
就算变量有值,你的写法也会出错:比如$namerecipe是Pasta的话,拼出来的SQL会是namerecipe =Pasta——字符串值没加单引号,SQL会把它当成关键字或字段名,直接报错。
3. 严重的SQL注入风险
直接把用户可控的变量拼接到SQL语句里是PHP开发的大忌,恶意用户可以通过构造参数篡改你的数据库(比如删除整张表),这绝对不能忽视。
正确的修复方式:使用预处理语句
推荐用PDO或者mysqli的预处理语句,既能解决语法问题,又能彻底避免SQL注入。下面是PDO的示例代码:
// 假设你已经建立了PDO数据库连接($pdo) $sql = "UPDATE rezepte SET namerecipe = :namerecipe, ingredient1 = :ingredient1, ingredient2 = :ingredient2, ingredient3 = :ingredient3, ingredient4 = :ingredient4, ingredient5 = :ingredient5, ingredient6 = :ingredient6, ingredient7 = :ingredient7, ingredient8 = :ingredient8, ingredient9 = :ingredient9, ingredient10 = :ingredient10, preparation = :preparation, cathegory1 = :cathegory1, cathegory2 = :cathegory2, cathegory3 = :cathegory3, difficulty = :difficulty, time = :time, amount = :amount, source = :source WHERE ID = :id"; // 预处理SQL语句 $stmt = $pdo->prepare($sql); // 绑定变量并执行 $stmt->execute([ ':namerecipe' => $namerecipe, ':ingredient1' => $ingredient1, ':ingredient2' => $ingredient2, ':ingredient3' => $ingredient3, ':ingredient4' => $ingredient4, ':ingredient5' => $ingredient5, ':ingredient6' => $ingredient6, ':ingredient7' => $ingredient7, ':ingredient8' => $ingredient8, ':ingredient9' => $ingredient9, ':ingredient10' => $ingredient10, ':preparation' => $preparation, ':cathegory1' => $cathegory1, ':cathegory2' => $cathegory2, ':cathegory3' => $cathegory3, ':difficulty' => $difficulty, ':time' => $time, ':amount' => $amount, ':source' => $source, ':id' => $id ]);
额外小提示
- 先确认所有变量都被正确赋值,用
var_dump()打印检查是最直接的方法 - 如果习惯用mysqli,同样支持预处理语句,原理和PDO一致
- 注意你拼写的
cathegory其实正确英文是category,不过只要数据库里的字段名和你写的一致就没问题
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

