我第一次使用PDO。
$result=$dbh->query($query) or die($dbh->errorinfo()."\n");
echo $result->fetchColumn();
$row = $result->fetch(PDO::FETCH_ASSOC);
以下代码的结果是$ row被初始化,即isset但是为空。
我无法弄到哪里出错了。提前谢谢
答案 0 :(得分: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 Manual ,以便更好地了解该主题。