我在使用 Mysql 查询时遇到错误


I have an error With Mysql Query

$sql="update item_master set department=$dept,make=$make,vat=$vat,cost=$mrp,packing=$pack,unit=$unit,exp_date=$ex,stock=$stock,description=$desc
where item_code=$id";
mysql_select_db('pds', $conn);
$result = mysql_query($sql);

错误是:

-id= 1dept=Ayurvedicmake=arihantname=sample2vat=4mrp=100pack=1*100无法运行查询: 您的 SQL 语法有误; 检查与您的MySQL服务器版本相对应的手册,了解在第2行的"其中item_code= 1"附近使用的正确语法

这里有一些错误。

看到你的许多变量都是字符串,它们需要被引号。

我发现的另一件事是 description=$descwhere 之间没有空间。

例如:如果$desc被定义为testing,那么MySQL将其解释为:

description=testingwhere item_code=$id

这将解释该错误,原因有几个,一个不带引号的变量和缺少的空格。

将代码更改为以下内容。

$sql="UPDATE item_master SET 
department = '$dept', make = '$make', vat = '$vat', cost = '$mrp', 
packing = $pack, unit = '$unit', exp_date= '$ex', stock = '$stock', 
description = '$desc' WHERE item_code=$id";

旁注:函数和子句最好使用大写字母。这有助于将它们与代码的其余部分区分开来。

另外,您的代码极易出现 SQL 注入。请考虑使用预准备语句,或暂时清理代码,直到您这样做。

另一个重要的说明。

如果您仍然遇到问题,那么可能会插入MySQL可能会抱怨的字符。因此,您将需要转义您的数据。

  • http://php.net/manual/en/function.mysql-real-escape-string.php

示例,并为其他人执行其余操作:

mysql_real_escape_string($dept);
  • 仔细检查列类型,使其与数据及其长度匹配。

引用:

  • https://en.wikipedia.org/wiki/Prepared_statement
  • http://php.net/manual/en/mysqli.prepare.php
  • http://php.net/manual/en/pdo.prepared-statements.php
  • https://en.wikipedia.org/wiki/SQL_injection

更改查询

$id需要喜欢'$id'

$sql="update item_master set department=$dept,make=$make,
vat=$vat,cost=$mrp,packing=$pack,unit=$unit,exp_date=$ex,
stock=$stock,description=$desc where item_code='$id'";
mysql_select_db('pds', $conn);
$result = mysql_query($sql);