duanjuete9206 2014-06-19 20:14
浏览 38
已采纳

调用成员函数非对象

I'm beginning with PHP and i need your help.

I create a try to list all members who has the same interest that the current_member( i mean the connected member ).

I write this :

$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);

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 ?

Thank's for your help.

  • 写回答

3条回答 默认 最新

  • douchun1961 2014-06-19 20:26
    关注

    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();
    

    (Since you are calling fetchAll(), I assume you are using PDO (and not MySQLi))

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?