0
I am having problems to do a search in mysql database inside a function in PHP, if I do the search outside the function works normally but I would like it to be done inside the function for me to call when you want.
Error: Undefined variable: conn in path\functions.php on line 4
and
Fatal error: Call to a member function query() on null in path\functions.php on line 4
My scheme.
<?php
$conn = new mysqli('localhost', 'root', '', 'banco');
if (mysqli_connect_errno()) {
printf('Connect failed: ', mysqli_connect_error());
exit();
}
$conn->select_db('banco');
?>
functions.php
<?php
function get_datas(){
$datas = array();
if($result = $conn->query("SELECT valor1, valor2, valor3 FROM tabela")){
while($row = $result->fetch_row()){
$datas[] = array(
'chave1' => $row[0],
'chave2' => $row[1],
'chave3' => $row[2]
);
}
return $datas;
}
$conn->close();
}
?>
index php.
<?php
include_once "db_connection.php";
include_once "functions.php";
$results = get_datas();
if(count($results) == 0){
echo 'Desculpe, mais não foram encontrados dados';
}
else{
foreach($results as $data){
echo $data['valor1'].'<br>';
echo $data['valor2'].'<br>';
echo $data['valor3'].'<br>';
}
}
?>
Problem is that the variable
$conn
within its function was not defined, which should be the connection to the database.– Wees Smith