Error when executing query within function

Asked

Viewed 24 times

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.

1 answer

2


One solution to your problem is to create a function with the connection and call it within the (s) other(s) 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 one researched in classes and métodos construtores, have a class that does all connection work, CRUD, well advance the service, at least to my view.

Browser other questions tagged

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