0

我是第一次使用 PDO。

$result=$dbh->query($query) or die($dbh->errorinfo()."\n");

echo $result->fetchColumn();

$row = $result->fetch(PDO::FETCH_ASSOC);

以下代码的结果是 $row 已初始化,即 isset 但为空。

我不知道我哪里出错了。提前致谢

4

1 回答 1

1

PDO 不执行旧式mysql_*代码do or die()

这是正确的语法:

try {
    //Instantiate PDO connection
    $dbh = new PDO("mysql:host=localhost;dbname=db_name", "user", "pass");
    //Make PDO errors to throw exceptions, which are easier to handle
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //Make PDO to not emulate prepares, which adds to security
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    $query = "SELECT * FROM `some_table`";

    //Prepare the statement
    $stmt = $dbh->prepare($query);
    //Execute it (if you had any variables, you would bind them here)
    $stmt->execute();

    //Work with results
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        //Do stuff with $row
    }
}
catch (PDOException $e) {
    //Catch any PDOExceptions that were thrown during the operation
    die("An error has occurred in the database: " . $e->getMessage());
}

您应该阅读PDO 手册,以更好地理解该主题。

于 2012-06-25T19:19:34.733 回答