Php mysql更新错误靠近';

Php mysql更新错误靠近';,php,mysql,Php,Mysql,你好,我有一个mysql问题,我真的需要帮助。我的更新代码: $update = mysql_query("UPDATE products SET stock = stock + $quantity WHERE id = $product_id") or die( mysql_error()); mysql\u错误说明如下: You have an error in your SQL syntax; check the manual that corresponds to your MySQL

你好,我有一个mysql问题,我真的需要帮助。我的更新代码:

$update = mysql_query("UPDATE products SET stock = stock + $quantity WHERE id = $product_id") or die( mysql_error());
mysql\u错误说明如下:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
这对我来说没有什么意义。顺便说一句,所有的变量都起作用

我知道我必须更新我的代码,但它必须起作用

更新:

$update = mysql_query("UPDATE products SET stock = stock + '1' WHERE id = '1'") or die( mysql_error());

这段代码现在可以工作了,所以它必须告诉我变量是字符串。如何将它们转换为int,我已尝试使用(int)$变量?

这里的问题是数据类型不匹配。在数据库中,id设置为Int。在PHP代码中,id设置为字符串。这会导致问题,因为将
$id
注入到查询中会在id的值(如果是字符串)周围添加单引号。这里有两个选项:

  • 将PHP代码中id的数据类型更改为Int。这可能不可能,具体取决于系统的设计方式
  • 将数据库中id的数据类型更改为Varchar。我不推荐这个
  • 更改您的查询。这可以通过将变量连接到查询中而不是将它们注入查询中来实现。
    id
    变量,例如:
    “更新产品集库存=库存+数量,其中id=”$产品标识

  • 正如Jay Blanchard所指出的,您应该查看并使用或尝试将intval与数量一起使用,因为它可能是一个字符串,您正试图用它来做一些奇怪的事情:

    $quantity = intval($quantity);
    $update = mysql_query("UPDATE products SET stock = stock + $quantity WHERE id = $product_id") or die( mysql_error());
    

    嘿,我刚刚将所有变量添加到intval,现在它没有显示任何错误,但它没有更新这应该是另一个问题。。。由于查询正常:请检查日志以查看错误的输出。好的,我刚刚对查询中的所有变量执行了intval($variable),但现在它没有显示错误或更新任何内容。您确定有需要更新的内容吗?可能
    id=1
    不在数据库中,或者
    $quantity
    为空,不向
    库存添加任何内容
    嘿,我发现当我使用
    (int)$variable
    将变量更改为int时,每个变量中的变量都变为0。为什么会这样,我如何修复它?您使用的是
    (int)$variable
    而不是
    intval($variable)
    ?请给我一些示例输入,这样我就可以看到发生了什么。我已经尝试了intval和int
    $id=intval($\u POST['id']);$productid=intval($_POST['productid']);$quantity=intval($_POST['quantity']);$workerid=intval($_POST['workerid'])
    
    $quantity = intval($quantity);
    $update = mysql_query("UPDATE products SET stock = stock + $quantity WHERE id = $product_id") or die( mysql_error());