問題描述
下午好!
我已經建立了一個到 Microsoft Access 數據庫(有效)的連接類.然而,我的問題在于我試圖使用這個類來執行一個簡單的 SQL 語句,但我收到錯誤消息:致命錯誤:調用非對象上的成員函數 fetchALL().
I have made a connection class to a Microsoft Access Database (which works). However my problem lies where I'm trying to use this class to execute a simple SQL statement and I receive the error message: Fatal error: Call to a member function fetchALL() on a non-object.
我對 PDO 還很陌生,在網上閱讀了很多文章,但都無濟于事.我想我理解我的問題,但并不完全理解,請有人能解釋一下這種情況,并可能就我收到錯誤消息的原因提供答案嗎?
I'm fairly new to PDO and have read a lot of articles online but to no avail. I think I understand my problem but not fully, please could someone shed some light on the situation and possibly provide an answer to why i'm getting the error message?
connectionClass.php
connectionClass.php
class connection{
public $con;
private $dbName;
function __construct(){
$this->dbName = $_SERVER["DOCUMENT_ROOT"] . "databaseyakety1new.mdb";
}
function connect(){
$this->con = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$this->dbName; Uid=Admin; Pwd=;");
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $this->con;
}
}
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
testIndex.php
testIndex.php
try{
include_once 'classesconnectionClass.php';
$con = new connection();
$pdoConnection = $con->connect();
$sql = $pdoConnection->prepare("SELECT * FROM celebs");
$result = $pdoConnection->exec($sql);
while ($row = $result->fetchALL(PDO::FETCH_ASSOC)) {
echo $row['firstname'];
echo $row['surname'];
}
} catch (Exception $e){
echo 'ERROR:'.$e->getMessage();
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
錯誤信息與這一行有關:
The error message is related to this line:
while ($row = $result->fetchALL(PDO::FETCH_ASSOC)) {
非常感謝任何幫助,謝謝!
Any help is greatly appreciated, thanks!
推薦答案
$result
只是一個布爾值,表示查詢是否成功.fetchAll
方法在 PDOStatement
上,所以它應該是:
$result
is just a boolean that indicates whether the query was successful or not. The fetchAll
method is on PDOStatement
, so it should be:
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
您也執行錯誤的語句,應該是:
You're also executing the statement wrong, it should be:
$result = $sql->execute();
您使用的方法是在不事先準備的情況下執行 SQL 字符串.你可以這樣做:
The method you used is for executing a SQL string without first preparing it. You could instead do:
$result = $pdoConnection->exec("SELECT * FROM celebs");
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
這篇關于致命錯誤:在非對象上調用成員函數 fetchALL() - 在 Microsoft Access 數據庫上使用 PDO的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!