开发者

fetch_assoc() issue with query

开发者 https://www.devze.com 2023-02-14 14:04 出处:网络
I have this function: function myFunc() { $conn=new mysqli(\'localhost\',\'root\',\'\',\'myDb\'); $conn->query(\'BEGIN\'开发者_高级运维);

I have this function:

    function myFunc()
{   
    $conn=new mysqli('localhost','root','','myDb');
    $conn->query('BEGIN'开发者_高级运维);
    $query="SELECT events_participants.userid,(SELECT COUNT(*) FROM events_participants WHERE events_participants.eventid=events.id FOR UPDATE) AS totRep FROM events INNER JOIN events_participants ON events_participants.eventid=events.id WHERE events.isConfirmed=3 AND reputationsUpdated=0";
    $result=$conn->query($query);
    if($result!==FALSE)
    {
        while(($row=$result->fetch_assoc())!==NULL)
        {

            $query="UPDATE users SET reputation=reputation+".$row['totRep'].",presences=presences+1 WHERE id=".$row['userid'];
            $result=$conn->query($query);
            if($result==FALSE)
            {
                $conn->query('ROLLBACK');
                throw new DatabaseErrorException();
            }
        }
        $query="UPDATE events SET reputationsUpdated=1 WHERE isConfirmed=3 AND reputationsUpdated=0";
        $result=$conn->query($query);
        if($result!==false)
        $conn->query('COMMIT');

        else
        $conn->query('ROLLBACK');
        throw new DatabaseErrorException();
    }
    else
    {
        throw new DatabaseErrorException();
    }   
}
myFunc();

If i test this it tells me: Call to a member function fetch_assoc() on a non-object..on the line where is the while loop.

But the fetch_assoc method over there actually populated my $row array (i tested echoing out $row['totRep']..so the problem is not in the query..

even if I test the same query in phpmyadmin it actually returns two rows..

where is the error?

what am I missing??

thank you again guys!


You are rewriting your $result variable numerous times.
You have to rename it.
If a variable going to be used further in the script (like $result one) it shouldn't be rewritten.
However, if it's one-time used variable, like $query one, it's possible to keep the same name for readability.


if($result) is the correct way.

if($result!=false) is also correct.

if($result!==false) is WRONG.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号