2012-07-04 70 views
6

我想開始使用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(); 
    } 

我得到的錯誤:

Fatal error: Call to undefined method PDO::execute() in ...


有人能幫我找到我的第一個PDO查詢嗎?

+6

Upvoted花時間切換到PDO。 – Mahn

回答

5

$db->prepare()返回一個PDOStatement其中有​​方法。

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

$db->prepare()返回PDOStatement對象。您需要撥打​​,而不是$db

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