Christophe Harris Christophe Harris - 3 months ago 25
MySQL Question

how do I solve PHP Fatal error: Call to a member function fetch_assoc()?

I have two tables,

user
and
category


user table :

enter image description here

category table :

enter image description here

user_id
in
user
table is the primary key and also serves as the foreign key in
category
table.

I want to display a list of titles by John Grisham but I'm getting :

Fatal error: Call to a member function fetch_assoc() on boolean in C:\wamp64\www\listprimarykeys.php on line 16


Line 16 is :

while($rows = $resultSet->fetch_assoc())


Here's my code. Is my
SELECT
statement alright?

<?php

$username = "John Grisham";

require_once('dbConnect.php');

$resultSet = $mysqli->query("SELECT cat_name FROM category INNER JOIN user ON category.user_id = user.user_id WHERE user.username = $username");

while($rows = $resultSet->fetch_assoc())

{
$user_id = $rows['cat_name'];
echo "<p>categories are $user_id";

}

?>

Answer

i cheeked this problem . you are one query problem , you must add two Quotes before and after variable $username in query String .

this code rights :

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$username = "ali" ;
$sql = "SELECT catname FROM category INNER JOIN user ON category.user_id = user.id WHERE user.username = '$username' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo " Name: " . $row["catname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();


?>

if this work is important better using this method in MySQLi for Prevent SQL injection : http://php.net/manual/en/mysqli.prepare.php