Php 对非对象调用成员函数fetch_assoc()

Php 对非对象调用成员函数fetch_assoc(),php,mysql,mysqli,Php,Mysql,Mysqli,因此,我对php有点陌生,当我遇到以下错误时,我正在尝试这样做: 致命错误:对第44行…/index.php中的非对象调用成员函数fetch_assoc 我的代码: if ($_SESSION['uid']){ $uid = $_SESSION['uid']; $result = $db->query("SELECT id,username FROM users WHERE id= '".$uid."'"); if ($result->num_rows){

因此,我对php有点陌生,当我遇到以下错误时,我正在尝试这样做: 致命错误:对第44行…/index.php中的非对象调用成员函数fetch_assoc

我的代码:

if ($_SESSION['uid']){
    $uid = $_SESSION['uid'];
    $result = $db->query("SELECT id,username FROM users WHERE id= '".$uid."'");
    if ($result->num_rows){
        session_destroy();
        echo "please <a href=\"login.php\">Login<a> to your account, or <a href=\"register.php\">Register<a> a new account! \n";
    }else{
        $row = $result->fetch_assoc();
        echo "Welcome back, <a href=\"index.php?act=profile&id=" .$row['id']."\">".$row['username']."</a> !\n";
    }
}
else {
    echo "please <a href=\"login.php\">Login<a> to your account, or <a href=\"register.php\">Register<a> a new account! \n";
}

我不明白我做错了什么

您的逻辑是反向的:当没有任何行时调用fetch\u assoc$result->num\u rows为0。如果$result->num_rows==0,则应改为执行此操作{.

查询没有结果,请尝试打印查询并手动执行会话启动了吗?您正在使用mysqli_uu连接,对吗?另外,您的查询可能成功,然后您破坏了会话,这就是您的代码所翻译的。您告诉它,如果查询很好,并且num_行找到了一行,请破坏会话;为什么?您的else{…}失败,因为您已将事情设置为向后;有点混乱。如果$result->num_rows{$row=$result->fetch_assoc;..}否则{session_destroy;echo please…}
$row = $result->fetch_assoc();