Select works perfectly, but when it is passed as function returns error

Asked

Viewed 41 times

0

I’m facing a dilemma that seems to be simple to solve, but I can’t see where the error is.

I have a SELECT COUNT(*) that works correctly, but when it is passed as a function the error occurs Warning: mysqli_query() expects Parameter 1 to be mysqli, null Given in "blah blah blah on line 35.

$conn =  mysqli_connect($hostName, $userName, $keyWord);
if (!$conn) {die('Falha ao estabelecer conexão com o banco de dados: '. mysqli_connect_error());};

if (!mysqli_select_db($conn, $dbName)) {
    $create_DB = "CREATE DATABASE IF NOT EXISTS " .$dbName;
    mysqli_query($conn, $create_DB);
    mysqli_select_db($conn, $DB);
}

echo $sql = 'SELECT COUNT(*) AS count_rows FROM tabelaDeTeste WHERE sexo = "masculino"';
echo "</br>";
$result = mysqli_query($conn, $sql) or die (mysqli_error($conn));
$count = mysqli_fetch_assoc($result);
//$count = mysqli_fetch_array($result);

if ($count["count_rows"] > 0) {
    echo $count["count_rows"];
} 

echo "</br>..........................................</br>";

function count_rows($table_name, $condition) {
    echo $sql = 'SELECT COUNT(*) AS count_rows FROM '.$table_name.' '.$condition; 
    echo "</br>";
    $result = mysqli_query($conn, $sql) or die (mysqli_error($conn));
    $count = mysqli_fetch_assoc($result);
    //$count = mysqli_fetch_array($result);

    if ($count["count_rows"] > 0) {
        echo $count["count_rows"];
    }
}

count_rows('tabelaDeTeste', 'WHERE sexo = "masculino"');

Return:

inserir a descrição da imagem aqui

Thank you for your attention and I await your return.

1 answer

-2


Within count_rows(), at the beginning of the function, place:

global $conn;
  • Marcelo has solved my problem. But I see so many rumors that using global variables is not a good practice that I ended up not even remembering that alternative. There’s another way you’re solving this without using global variables?

  • 1

    @Skyline Just pass the connection as a parameter: function count_rows($conn, $table_name, $condition) { etc } and to call the function: count_rows($conn, 'tabelaDeTeste', 'WHERE sexo = "masculino"')

Browser other questions tagged

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