2012-08-07 45 views
2

我開始了與PDO,並試圖將這段代碼,它的工作原理:這個PHP PDO例程有什麼問題?

$dbh->query("INSERT INTO sugestao (id, fbid, username, latitude, longitude, endereco, categoria, titulo, descricao, foto) 
         VALUES (null, 
          '".$fbid."', 
          '".$username."', 
          '".$lat."', 
          '".$lon."', 
          '".$endereco."', 
          '".$categoria."', 
          '".$titulo."', 
          '".$descricao."', 
          '".$foto."')"); 

有了這一個,這似乎更安全,更好地維護,而且也應該讓我放心地獲得最後插入的ID :

$dbh->beginTransaction(); 

    $dbh->prepare("INSERT INTO sugestao (id, fbid, username, latitude, longitude, endereco, categoria, titulo, descricao, foto) 
         VALUES (null, :fbid, :username, :lat, :lon, :endereco, :categoria, :titulo, :descricao, :foto)"); 
    $dbh->bindParam(":fbid", $fbid); 
    $dbh->bindParam(":username", $username); 
    $dbh->bindParam(":lat", $lat); 
    $dbh->bindParam(":lon", $lon); 
    $dbh->bindParam(":endereco", $endereco); 
    $dbh->bindParam(":categoria", $categoria); 
    $dbh->bindParam(":titulo", $titulo); 
    $dbh->bindParam(":descricao", $descricao); 
    $dbh->bindParam(":foto", $foto); 
    $dbh->execute(); 
    $lastid = $dbh->lastInsertId(); 
    $dbh->commit(); 

這第二個,給我一個500服務器錯誤。任何線索?

+0

什麼是從您的apache/php錯誤日誌的錯誤消息? – Matt 2012-08-07 14:06:53

+0

VALGES('null',':fbid',':username','''') ':lat',':lon',':endereco',':categoria',':titulo',':descricao',':foto')「);' 嘗試一下。 – 2012-08-07 14:07:51

+1

PDO的要點是使用佔位符。在你的第一個例子中,你側重於PDO的任何好處,並創建**巨大的錯誤。 @grunk有答案。 – tadman 2012-08-07 15:51:11

回答

4

bindParamexecute和從PDOStatement功能,而不是從PDO:

$statement = $dbh->prepare(...); 
$statement->bindParam(); 
$statement->execute(); 
2

$dbh->bindParam()沒有定義。

// Create the statement 
$stmt = $dbh->prepare("INSERT INTO sugestao (id, fbid, username, latitude, longitude, endereco, categoria, titulo, descricao, foto) 
         VALUES (null, :fbid, :username, :lat, :lon, :endereco, :categoria, :titulo, :descricao, :foto)"); 

// Bind parameters 
$stmt->bindParam(":fbid", $fbid); 
// ... 
$stmt->bindParam(":foto", $foto); 

// Execute the statement 
try { 
    $dbh->beginTransaction(); 
    $stmt->execute(); 
    $dbh->commit(); 
} catch (PDOExecption $e) { 
    $dbh->rollback(); 
    // Do whatever you want 
} 

// Read last ID on the statement 
$lastId = $stmt->lastInsertId();