2

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

4

2 回答 2

4

bindParam并且execute是来自PDOStatement而不是来自 PDO 的函数:

$statement = $dbh->prepare(...);
$statement->bindParam();
$statement->execute();
于 2012-08-07T14:11:01.160 回答
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();
于 2012-08-07T14:11:52.400 回答