gpt4 book ai didi

php - PDO - 调用非对象上的成员函数 fetch()?

转载 作者:行者123 更新时间:2023-11-29 00:54:16 26 4
gpt4 key购买 nike

我查看了关于此的所有其他帖子,但没有一个能确切地指出我的问题所在,所以我们开始吧:

$dbh 存储我的 PDO 连接,如果我对其进行 var dump,它返回:

object(PDO)#1 (0) { }

所以我知道我的 PDO 连接正常。然后我使用 $sth 来保存我的查询:

$c = 2;
$sth = $dbh->query("SELECT * FROM table WHERE ID = " . $c);

然后为了确保这是有效的,我做了:

echo $sth->rowCount();

返回值为 6。所以我知道它正在抓取一些行。检查我的问题的下一步是像下面这样获取一行:

$row = $sth->fetch()
print_r($row);

这返回了一行(它应该如此),其中 $row 数组完全按照我的预期填充(列名作为键,列值作为数组值)。

到目前为止,我们还不错。一旦我将 $row = $sth->fetch() 移动到 while 循环中,我的脚本就会失败,它返回的错误是: Call to a member function fetch() on a non-object

这是我的 while 循环:

while($row = $sth->fetch()){
//while loop stuff here
}

我知道它与循环条件有关,因为即使我注释掉中间的所有内容,它仍然无法正常工作。我究竟做错了什么?为什么这行不通?我对此感到非常困惑,因为它过去曾与我完成的所有 PDO 一起工作,但由于某种原因它在此脚本中失败了。

如果有人有任何提示或可以提供帮助的东西,我们将不胜感激。

编辑 由于 ninetwozero 的帖子有效,我发布了我的类(class)以及基本上我必须弄清楚的所有内容。

class html_elements {

var $units;
var $useMaps;
var $cid;
var $uid;
var $companyMoney;
var $currCity;
var $terminals;
var $termLocs;
var $cityArray;
var $cargoArray;
var $cargo;
var $tid;
var $truckArray;
var $load;
var $cityID;
var $cargoID;
var $xp;
var $gasPrice;
var $warning;

function __construct($u, $maps, $c, $userID, $cMoney, $dbh, $city, $tid, $xp){
$this->units = $u;
$this->useMaps = $maps;
$this->cid = $c;
$this->uid = $userID;
$this->companyMoney = $cMoney;
$this->currCity = $city;
$this->terminals = array();
$this->termLocs = array();
$this->cityArray = array();
$this->cargoArray = array();
$this->cargo = array();
$this->tid = $tid;
$this->truckArray = array();
$this->load = 0;
$this->cityID = array();
$this->cargoID = array();
$this->xp = $xp;
$this->gasPrice = 0;

$sth = null;
$sth = $dbh->query("SELECT * FROM tblCTerminals WHERE companyID = " . $c);
//THIS LOOP FAILS
while($row = $sth->fetch()){
$this->termLocs[] = $row['Location'];
}
}

然后在另一个包含我的类文件的文件中是:

$h = new html_element($u->get_units(), $u->get_maps(), $u->get_company(), $u->get_user_id(), $c->get_money(), $dbh, $u->get_city(), $u->get_truck_id(), $u->get_xp());

这些 getter 中的每一个都有效,我对它们进行了测试。另外 $dbh 是我的连接文件所使用的,它在其他任何东西之前都包含在内。所以我知道所有这些都在起作用。

最佳答案

我不得不说你遇到了一个非常有趣的错误,所以让我们尝试一些事情来查明原因:

if( $sth == null ) die('My sth is null at #1');
while( $row = $sth->fetch() ) {
if( $row == null ) die('My row is null at #2');
echo '<pre>';
print_r($row);
echo '</pre>';
}

让我知道这告诉你什么。

编辑:

$sql = 'SELECT * FROM tblCTerminals WHERE companyID = ' . $c;
if( intval($c) == 0 ) { die('Aaaaaaaaaa.......aaaaah.');
foreach ($dbh->query($sql) as $row) {
echo '$row[\'Location\'] is: ' . $row['Location'] .'<br />';
$this->termLocs[] = $row['Location'];
}

关于php - PDO - 调用非对象上的成员函数 fetch()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6890577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com