using MySQLi within CLASS [closed]

0

Hello, I have a problem, I have some queries to do, I wanted to leave it inside class, I am doing the following code:

<?php
class MySQL {
    private $user;
    private $password;
    private $database;
    private $host;

    public function __construct($user, $password, $database, $host="localhost"){
        $this->user     =   $user;
        $this->password =   $password;
        $this->database =   $database;
        $this->host     =   $host;

        $this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->database);
        if (mysqli_connect_errno()) {
            die('FATAL ERROR: Can not connect to SQL Server.');
            exit();
        }
    }

    public function _query($qr)
    {
        $this->result = $this->mysqli->query($qr);
        return $this->result;
    }

    public function _close()
    {
        $this->mysqli->close();
    }
}

To call, I do:

    <?php
        session_start();
        $connect = new MySQL(UserMySQL, PassMySQL, DataBaseMySQL, ServerMySQL);
function test(){
        $search =   $connect->_query("SELECT value FROM tab2 WHERE type='".$type."'");
        $search =   $connect->_query("SELECT * FROM tab1 WHERE urlName='".$subName."'");
    }
    test();

But it returns me error. Call a member function _query () on a non-object in ..........

    
asked by anonymous 11.08.2016 / 20:12

1 answer

1

You have failed to declare global $ connect variable within the function, like this:

function test(){
    global $connect;
    $search =   $connect->_query("SELECT value FROM tab2 WHERE type='".$type."'");
    $search =   $connect->_query("SELECT * FROM tab1 WHERE urlName='".$subName."'");
}

I apologize the community for making this mistake, anyway, now whoever has this doubt will know hahaha

    
11.08.2016 / 20:55