这个PHP PDO例程有什么问题


What is wrong with this PHP PDO routine?

我从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 服务器错误。有什么线索吗?

bindParamexecute是来自PDOStatement而不是PDO的函数:

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

定义$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();