【问题标题】:Error when executing prepared statement in MySQL在 MySQL 中执行准备好的语句时出错
【发布时间】:2015-03-25 23:57:55
【问题描述】:

当我尝试运行以下准备并执行 INSERT 语句的函数时,我不断收到来自 MySQL 的错误:

public static function addProduct($db, $barcode, $product_name, $price) {
    $quantity =  1;

    $query = "INSERT INTO Product (BarCode, PName, Price, QuantityInStock) VALUES (?, ?, ?, ?)";
    $stmt = $db->stmt_init();
    $stmt->prepare($query);
    $stmt->bind_param('isii', $barcode, $product_name, $price, $quantity);
    $stmt->execute();

    $result = $db->query($query);
    if (!$result || $db->affected_rows == 0) {
        echo "<h2>ARG: *$query* . ERROR: " . $db->error . "</h2>";
    }
}

这是我得到的输出:

ARG:插入产品(条形码、PName、价格、QuantityInStock)值(?、?、?、?)。错误:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“?,?,?,?)”附近使用正确的语法

这些是我尝试插入的正确字段,每个变量都有一个值。这些也是 bind_param() 中的正确类型。

有人有什么想法吗?谢谢。

【问题讨论】:

  • 一件快事。价格可能不是整数。也许是双倍的。
  • @Burak, 'iisi': int int string int. php.net/manual/en/mysqli-stmt.bind-param.php
  • @dudeman,PName 是 varchar(50),其他都是 int(11)
  • $result = $db-&gt;query($query) 不要这样做。您已经执行了该语句。 $stmt-&gt;execute() 的结果会告诉你它是否有效,$stmt-&gt;affected_rows 会告诉你执行了多少次插入
  • 看到准备好的语句并且没有全局变量进行更改真是令人耳目一新。

标签: php mysql mysqli prepared-statement


【解决方案1】:

这是你的问题:

$result = $db->query($query);

您正在第二次运行查询。

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 2017-09-15
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 2011-09-16
    相关资源
    最近更新 更多