这个PHP PDO例程有什么问题?

时间:2012-08-07 14:05:35

标签: php mysql pdo

我开始使用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服务器错误。有线索吗?

2 个答案:

答案 0 :(得分:4)

bindParamexecute来自PDOStatement,而不是来自PDO:

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

答案 1 :(得分: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();