Error executing query within function

0

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>';
        }
    }
?>
    
asked by anonymous 14.07.2018 / 13:09

1 answer

2

One solution to your problem is to create a function with the connection and call it within the other function (s):

function conn(){
    $conn = new mysqli('localhost', 'root', '', 'banco');
    if (mysqli_connect_errno()) {
        printf('Connect failed: ', mysqli_connect_error());
        exit();
    }
    $conn->select_db('banco');
    return $conn;
}

function get_datas(){
    $datas = array();
    $conn = conn();
    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();
}

But of a searched in classes and métodos construtores , to have a class that does all the connection work, CRUD, advances the service well, at least in my view.

    
14.07.2018 / 14:08