Error "Warning: mysqli_query() expects Parameter 1 to be mysqli, null Given"

Asked

Viewed 15,542 times

-4

I am developing a PHP API, which is hosted on Hostinger. However, when I do the SQL query on Mysqli, I get the same error no matter what changes I make to the code:

Warning: mysqli_query() expects Parameter 1 to be mysqli, null Given android_connect/get_all_products.php on line 20

When I change all the code to Mysql, it informs that Mysql is already old and asks me to do it in Mysqli.

Is there a solution to this error? Without it, and you can help, I thank you.

db_connect.php

<?php

/**
 * Uma classe de conexão ao banco.
 */
class DB_CONNECT {

    // Construtores
function __construct() {
    // Realiza a conexão.
    $this->connect();
}

// Desconstrutor.
function __destruct() {
    // Encerra a conexão.
    $this->close();
}

  /**
 * Função para conectar-se ao banco.
 */
function connect() {
    //Importa as variaveis da conexão.
    require_once __DIR__ . '/db_config.php';

    // Conecta ao banco com as informações importadas.
    $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD)or die(mysqli_error());

    // Seleciona o banco.
    $db = mysqli_select_db($con, DB_DATABASE)  or die(mysqli_error());

        // Retorna os cursores.
        return $con;
    }

    /**
     * Função que encerra a conexão,
     */
    function close() {
        // Fecha a conexao.
        mysql_close();
    }

}

?>

get_all_product.php

<?php
/*
 * Lista todos os itens que estão no banco.
 */

// Array para resposta do JSON
$response = array();


// Inclui as classes de conexão.
require_once __DIR__ . '/db_connect.php';

// Conecta-se ao banco.
$db = new DB_CONNECT();


// Pega os produtos da tabela AN_CAR
$result = "SELECT * FROM all_car";
$query = mysqli_query($con) or die (mysqli_error($con));

// Checa se há campos vazios
if (mysql_num_rows($result) > 0) {
    // Se há campos preenchidos no banco, loopa todos os resultados e puxa. 

    $response["an_car"] = array();

    while ($row = mysql_fetch_array($result)) {
        // Array de todos os itens.
        $product = array();
        $product["id"] = $row["id"]; 
        $product["modelo"] = $row["modelo"];
        $product["marca"] = $row["marca"];
        $product["ano"] = $row["ano"];
        $product["motor"] = $row["motor"];
        $product["imagem"] = $row["imagem"];
        $product["preço"] = $row["preço"];



        array_push($response["all_car"], $product);
    }
    // Busca bem sucedida.
    $response["success"] = 1;

    // Mostra os resultados em JSON.
    echo json_encode($response);
} else {
    // Caso não encontre nada:
    $response["success"] = 0;
    $response["message"] = "Não há itens.";

    // echo no users JSON
    echo json_encode($response);

}
?>

1 answer

2


Your code contains several errors, which using mysqli or would not occur, understand this as a constructive criticism:

First you can call the bank next to the mysqli_connect:

function connect() {
     require_once __DIR__ . '/db_config.php';

     $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE) or die(mysqli_error());

     return $con;
}

Something else in connect the return $con will not return to the constructor object, but rather to the "nothing", see:

function __construct() {
    // Realiza a conexão.
    $this->connect();
}

You can create a method to recover the connection, the class should look like this:

<?php
class DB_CONNECT
{
    private $con;

    function __construct() {
        $this->connect();
    }

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

    function connect()
    {
        if ($this->con) {
            return NULL;
        }

        require_once __DIR__ . '/db_config.php';
        $this->con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE) or die(mysqli_error());
    }

    function getConnection()
    {
        return $this->con;
    }

    function close()
    {
        mysqli_close($this->con);
    }
}

I didn’t understand the necessity of the class, the mysqli itself can be written in Oop, but I won’t go into detail.

Another very important thing, you’re trying to access $con outside the class, but it is in the scope of the class and not outside, which makes it impossible to access directly, then with the method getConnection do so:

$db = new DB_CONNECT();
$con = $db->getConnection();

The other problem is that here you are not passing the query, only the connection:

 $result = "SELECT * FROM all_car";
 $query = mysqli_query($con) or die (mysqli_error($con));

And you passed a string to mysql_fetch_array, out that you have to use mysqli at all, no use one part use mysqli api and the other the old api:

 while ($row = mysql_fetch_array($result)) {

Do so:

$db = new DB_CONNECT();
$con = $db->getConnection();

$query = "SELECT * FROM all_car";
$result = mysqli_query($con, $query) or die(mysqli_error($con));


while ($row = mysqli_fetch_assoc($result)) {
}

Read and do exactly as this in the documentation, it serves to help:

Read the examples, see the comments, follow what the documentation says from the parameters to what kind of value the function returns, not only for mysqli, but for any language that provides a documentation.

  • Opa, Guilherme, I appreciate the help... I made the changes as suggested, but the error persists. When I put $query = "SELECT * FROM all_car"; $result = mysqli_query($con, $query) or die (mysqli_error($con)); , the error remains the same. What is wrong? !

  • @Willcunha sorry I corrected the code. Missed the second parameter :)

  • Guilherme... man, even making the changes, he keeps returning the same error. Is it some PHP configuration error?

  • @Willcunha edited the answer, please read it all again.

  • William, I made the suggested changes and, the error remains. I thank you for your help!

Browser other questions tagged

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