I'm having trouble doing a mysql query within a PHP function, if I do the search function off normally it works but I'd like it to be done inside the function for me to call when I want.
Error: Undefined variable: conn in path\functions.php on line 4
e
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>';
}
}
?>