调用非对象的成员函数 [英] call to a member function non-object
问题描述
我刚开始接触 PHP,我需要你的帮助.
I'm beginning with PHP and i need your help.
我尝试列出与 current_member 有相同兴趣的所有成员(我的意思是已连接的成员).
I create a try to list all members who has the same interest that the current_member( i mean the connected member ).
我是这样写的:
$current_members = params('current_member');
$members_all = option('db')->query('SELECT * FROM members WHERE interest = $current_members["interest"] ORDER BY lastname, firstname')->fetchAll();
set('members_all', $members_all);
当我进入我的页面时出现错误:致命错误:在非对象上调用成员函数 fetchAll()
When I go on my page I have the error : Fatal error: Call to a member function fetchAll() on a non-object
在我看来,我只是这样写:
And in my view I just write this :
<h2 id="member-<?= $member['id'] ?>">
<?= avatar_tag($member,'30x30') ?>
<a href="<?=member_url_for($member)?>"><?=$member['firstname']?><small> <?= $member['lastname'] ?></small></a>
</h2>
我不明白这个错误,任何人都可以帮助我吗?
I dont understand this error, anyone can help me ?
感谢您的帮助.
推荐答案
不要像您现在所做的那样将调用链接到 query()
和 fetchAll()
.这是不好的做法.永远不要假设您的查询有效,始终检查是否有效.
Do not chain calls to query()
and fetchAll()
like you are doing. That's bad practice. Never assume your query worked, always check to see if it did.
$db = option('db');
$query = $db->query('SELECT ...');
if($query === FALSE){
print_r($db->errorInfo());
die;
}
$members_all = $query->fetchAll();
(由于您正在调用 fetchAll()
,我假设您使用的是 PDO(而不是 MySQLi))
(Since you are calling fetchAll()
, I assume you are using PDO (and not MySQLi))
另外,不要尝试将变量连接到您的 SQL 查询中.(P.S. 你甚至没有这样做,你使用的是单引号,所以 $current_members["interest"]
没有被读取为变量)这只是要求进行 SQL 注入攻击.您要做的是使用准备好的语句.
Also, do not try to concatenate variables into your SQL query. (P.S. You're not even doing that, you are using single quotes, so $current_members["interest"]
is not being read as a variable) That's just asking for an SQL injection attack. What you want to do is use prepared statements.
$db = option('db');
$query = $db->prepare('SELECT * FROM members WHERE interest = ? ORDER BY lastname, firstname');
$exec = $query->execute(array($current_members['interest']));
if($exec === FALSE){
print_r($query->errorInfo());
die;
}
$members_all = $query->fetchAll();
这篇关于调用非对象的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!