Call to a member function fetch_assoc () on a non-object

0

I used MySQL and PHP in wampserver, now coma last 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;
?>

It is giving error:

  

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

    
asked by anonymous 29.02.2016 / 20:21

2 answers

3
  

Call to a member function fetch_assoc ()

When encountering the above error, it means that your query failed, to know the source of the error check the line before the call fetch_assoc() which is $mysqli->query($sql); .

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

In your case, there are single quotes in the table name, which causes a syntax error, single quotes are only for values and not for escaping 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, it identifies the category of the error and provides a valuable hint on how to solve the problem. 1064 means syntax error.

Code with error checking:

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

Or even

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

Recommended reading:

Documentation - MySQLi-> error

A MySQL query with ciphers vs without

SQL State MySQL List

    
29.02.2016 / 20:45
1

Use the fetch_array (MYSQLI_ASSOC)

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 MySQL database connection class 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;   
        }
    }
}
    
29.02.2016 / 20:40