第一次使用PDO时出现问题

时间:2012-07-04 16:05:27

标签: php mysql pdo

我正在尝试开始使用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()


有人可以帮助我让我的第一个PDO查询工作吗?

4 个答案:

答案 0 :(得分:5)

$db->prepare()会返回PDOStatementexecute()方法。

$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']
));

答案 1 :(得分:4)

$db->prepare()会返回PDOStatement个对象。您需要致电execute(),而不是$db

答案 2 :(得分:1)

我将ya引用到示例中...... prepare创建了一个语句,并且就是你在...上运行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));
?>

答案 3 :(得分:1)

prepare的调用会返回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']));