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:
Thank you for your attention and I await your return.
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?
– Skyline
@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"')
– hkotsubo