Call to a Member Function fetch_assoc() on a non-object

Asked

Viewed 3,194 times

1

I used Mysql and PHP on wampserver, now with the latest version it uses Mysqli I’m having problems with the following command:

// Executa uma consulta que pega cinco notícias
$sql = "SELECT * FROM 'usuarios'";
$query = $mysqli->query($sql);
while ($dados = $query->fetch_assoc()) {
    echo 'ID: ' . $dados['id'] . '';
    echo 'Título: ' . $dados['nome'] . '';
}
echo 'Registros encontrados: ' . $query->num_rows;
?>

Is making a mistake:

Call to a Member Function fetch_assoc() on a non-object in C: wamp www query.php on line 17

  • Your query has an error, it will not quote simple in table name.

  • 2

    The question was edited and approved but the formatting was not applied. Galera ta approving on automatic, without checking if the edition actually improves the reading of the question.

  • 1

    Thank you very much, I’m picking up a bit with mysqli, so far I haven’t been able to make a login system with session with it. More I’m looking for, VLW

  • Could you mark the answer that solved the problem as accepted? is a green light. See How and why to accept an answer?

2 answers

3

Call to a Member Function fetch_assoc()

When you come across the above error, it means that your query failed, to know the origin of the error check the previous line to call fetch_assoc() that is $mysqli->query($sql);.

to get some hint of what was the real problem see what is the return of mysqli->error.

In your case, it has simple quotes in the table name, which causes a syntax error, simple quotes are only for values and not to escape identifier names.

$sql = "SELECT * FROM 'usuarios'";

The error message returned is:

Error Code: 1064. You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near '''table'' at line

That 1064 code is called SQL State and it identifies what the error category is and provides a valuable tip on how to solve the problem. 1064 means syntax error.

Code with error check:

$query = $mysqli->query($sql) or die($mysqli->errno .' - '. $mysqli->error);
while ($dados = $query->fetch_assoc()) {

Or else

$query = $mysqli->query($sql);
if(!query){
    echo 'erro: SQLState: '.  $mysqli->errno .' - '. $mysqli->error;
    exit;
}

Recommended reading:

Documentation - Mysqli->error

A Mysql query, with crases vs without

List of SQL State Mysql

2

Use the fetch_array(MYSQLI_ASSOC command)

require_once("conexao.php");        // Neste arquivo você cria a classe de conexão com o banco
$sql = "SELECT * FROM usuarios";

$con = Conexao::getInstanciar();    // Faz a conexao com o banco atraves de uma classe de conexao
$query = $con->executar($sql);

    while ($dados = $query ->fetch_array(MYSQLI_ASSOC)) {
        echo 'ID: ' . $dados['id'] . '<br>';
        echo 'Título: ' . $dados['nome'] . '';
    }
    echo '<p>Registros encontrados: ' . $query ->num_rows . '</p>';

If you need to, this is the connection class with the Mysql database conexao.php

class Conexao extends MySQLi {

    private static $host = 'localhost';
    private static $user = 'root';
    private static $pass = '*****';
    private static $base = 'seuBanco';

    private static $conectado = false;
    private static $instaciado = NULL;

    public function __destruct(){
        $this->close(); 
    }

    public static function getInstanciar() {
        if (NULL == self::$instaciado){
            self::$instaciado = new self(); 
        }
        return self::$instaciado;
    }

    public function conectar(){
        if (!self::$conectado) {
            parent::__construct(self::$host, self::$user, self::$pass, self::$base);
        parent::set_charset('utf8');

            if (mysqli_connect_errno()) {
                throw new Exception('A conexao falho: ' . mysqli_connect_error());  
            }
            self::$conectado = true;
        }
    }

    public function fechar(){
        if (self::$conectado) {
            parent::close();
            self::$conectado = false;   
        }
    }

    public function executar($pSQL) {
        $this->conectar();
        $resultado = parent::query($pSQL);

        if ($resultado) {
            return $resultado;  
        } else {
            echo '<b>Erro na Query:</b><br>' . $pSQL;   
            echo '<br><br>';
            echo '<b>Erro:</b><br>' . mysqli_error($this);  
            echo '<br><br>';
            echo '<b>Número:</b>' . mysqli_errno($this) . '<br><br>';   
        }
    }

    public function estado(){
        if (@mysqli_ping($this)){
            return true;
        } else {
            return false;   
        }
    }
}
  • 1

    Eduardo, I removed the tag markdown that you entered in the fictional php filename, because it was not relevant to this use. the tag markdown is for when you want to reference an existing tag on the site, so when you click on it, the user will be taken to a search with the content of the site referring to that tag.

  • 1

    No problem. I’m still getting used to the features of stackoverflow. It’s perfect and thanks for the tip. : )

  • The answer still has the same question problem, syntax error :P removes those simple user quotes in select.

  • Well noted @rray. Removed and thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.