简体   繁体   中英

trying to display records from database using php

this is my first question here so feedback on how to improve my questions would be appreciated.

I am trying to display records from a database using PHP. Here is the code

<?php
$dbConn = new mysqli('localhost', 'twa037', 'twa037Dg', 'autoservice037');
if($dbConn->connect_error) {
    die("failed to connect to the database: " . $dbConn->connect_error);
}
else
{
    echo "success";
}

    $sql = "select * from customer ";
    if ($dbConn->query($sql) ) 
        {
            echo "query successful";    
        }

     while($row = $sql->fetch_assoc())  {

    echo $row['familyName'];
    } 

    $dbconn->close();

    ?>

I am able to connect to the database and also the query appears to be working fine as it is displaying "success" and "query successfull". However, I am getting this error

Fatal error: Uncaught Error: Call to a member function fetch_assoc() on string

Before you guys suggest this could be a duplicate of another post, I have noticed that in the other posts they have used the same code as I have without an issue.

mysqli_query returns a result on that you can call fetch_assoc() . not on the querystring itself.

if ($result = $dbConn->query($sql) ) 
    {
        echo "query successful";    
    }

 while($row = $result->fetch_assoc())  {

more informations you can find here

while($row = $sql->fetch_assoc()) <=> while($row = $dbConn->query($sql)->fetch_assoc()) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM