Error "Warning: mysqli_query () expects parameter 1 to be mysqli, null given" [closed]

-4

I'm developing an API in PHP, which is hosted by Hostinger. However, when I do the SQL query in MySQLi, I get the same error, no matter what changes I make in 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 for MySQL, it informs that MySQL is already old and asks me to do it in MySQLi.

Is there any solution to this error? Without it, and you guys can help, I appreciate it.

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);

}
?>
    
asked by anonymous 30.11.2015 / 20:23

1 answer

2

Your code contains a number of errors, which would not occur if you used mysqli , understand this as constructive criticism:

First you can call the bank next to 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;
}

Another thing in connect return $con will not return to the constructor object, but to nothing, see:

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

You can create a method to retrieve 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 do not understand the need of the class, the proper mysqli can be written in oop, but I will not go into details.

Another very important thing, you are 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 getConnection do so:

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

The other problem is that here you are not passing the query, just 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 , outside you have to use mysqli at all, there is no use of one part to use mysqli api and in the other the old api:

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

Do this:

$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 like this in the documentation, it helps:

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 documentation .

    
30.11.2015 / 20:32