6

我正在尝试开始使用 PDO,但遇到了一些麻烦。这是我的原始代码:

    $query = "
              UPDATE `products` 
              SET `product_qty` = '{$_GET['product_qty']}'
              WHERE `product_id` = '{$_GET['product_id']}'
    ";

    mysql_query($query) or die(mysql_error());

这很好用,但是当我尝试将其转换为 PDO 语法时:

    $db->prepare('
    UPDATE products 
    SET product_qty = :product_qty
    WHERE product_id = :product_id
    ');

    try 
    {
        $db->execute(array(':product_qty' => $_GET['product_qty'], ':product_id' => $_GET['product_id']));
    }
    catch (PDOException $e) 
    {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }

我得到错误:

致命错误:调用未定义的方法 PDO::execute() in ...


有人可以帮我完成我的第一个 PDO 查询吗?

4

4 回答 4

5

$db->prepare()返回PDOStatement具有该execute()方法的a。

$stmt = $db->prepare('UPDATE products 
    SET product_qty = :product_qty
    WHERE product_id = :product_id');

$stmt->execute(array(
    ':product_qty' => $_GET['product_qty'], 
    ':product_id' => $_GET['product_id']
));
于 2012-07-04T16:07:16.537 回答
4

$db->prepare()返回一个PDOStatement对象。您需要调用execute()它,而不是调用$db.

于 2012-07-04T16:07:15.943 回答
1

我向你推荐这个例子......准备创建一个语句,它就是你运行execute()......

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>
于 2012-07-04T16:08:54.180 回答
1

调用prepare返回 a PDOStatement,这就是您需要的execute。尝试以下操作:

$sth = $db->prepare('
  UPDATE products 
  SET product_qty = :product_qty
  WHERE product_id = :product_id
');

$sth->execute(array(':product_qty' => $_GET['product_qty'], ':product_id' => $_GET['product_id']));
于 2012-07-04T16:09:34.710 回答