Fatal error: Call to undefined function fetch_assoc() What Gives?

旧时模样 提交于 2020-01-08 06:26:47

问题


Im trying to display users from the database on the page after login but i keep getting an error message:

Fatal error: Call to undefined function fetch_assoc()

here is the code:

    <?php
session_start(); ?>

<link rel="stylesheet" href="form.css">
<div class="body content">

    <div class="welcome">
        <div class="alert alert-success"><?= $_SESSION['message'] ?></div>
        <img src="<?= $_SESSION['avatar'] ?>"><br />
        Welcome <span class="user"><?= $_SESSION['username'] ?></span>

        <?php
        $mysqli = new mysqli("localhost","user","password","database");
        //Select queries return a resultset
        $sql = "SELECT username, avatar FROM users";
        $result = $mysqli->query($sql); //$result = mysqli_result object
        //var_dump($result);
        ?>

        <div id='registered'>
        <span>All registered users:</span>

        <?php
        //while($row = $result->fetch_assoc()){ //returns associative array of fetched row
         while($row = fetch_assoc($result)){ //returns associative array of fetched row
            //echo '<pre>';
            //print_r($row);
            //echo '</pre>';
            echo "<div class='userlist'><span>$row[username]</span>";
            echo "<img src='$row[avatar]'></div>";
        }
        ?>  
        </div>
    </div>
</div>

回答1:


This is how you do this, you're mixing object oriented and procedural:

while($row = $result->fetch_assoc()){ //returns associative array of fetched row
            //echo '<pre>';
            //print_r($row);
            //echo '</pre>';
            echo "<div class='userlist'><span>$row[username]</span>";
            echo "<img src='$row[avatar]'></div>";
        }



回答2:


Here is correct script for procedural connection to database:

<?php    
    $con = mysqli_connect("localhost","root","","db1");
    $sql = "SELECT username, avatar FROM users";
    $result = mysqli_query($con,$sql);
    $row = mysqli_fetch_assoc($result);
    echo $row["username"] . " " . $row["avatar"] . "<br>";
    mysqli_close($con);
?>


来源:https://stackoverflow.com/questions/43596622/fatal-error-call-to-undefined-function-fetch-assoc-what-gives

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!