2012-08-07 46 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();