Mihkel Viilveer
Mihkel Viilveer

Reputation: 432

Mysql queries in object

I've written a object oriented style for a month so far and I'm now wondering which is the right approach with sql queries. So for instance I have function getPlayerData in class. So Which way is better - 1) Do a mysql procedure outside of class and give fetched array to getPlayerData 2) Do all the procedure in class

And If you suggest the second case then should I start every function with global $variable which has the mysqli instance started?

Sorry if I don't use right terms, you can always correct me. Thanks!

Upvotes: 1

Views: 78

Answers (1)

user399666
user399666

Reputation: 19879

Instead of giving each class function a global variable, you could do something like:

class Test{

    protected $mysqli = null;

    function __construct($mysqli = null){
        $this->mysqli = $mysqli;
    }

    public function setMySqli($mysqli){
        $this->mysqli = $mysqli;
    }

    public function getSomething(){
        $result = $this->mysqli->query("SELECT something FROM table");
        //do something with result here
        return $result;
    }

}

Allowing you to use your object like so:

$test = new Test($mysqli);
$result = $test->getSomething();

or

$test = new Test();
$test->setMySqli($mysqli);
$result = $test->getSomething();

Upvotes: 1

Related Questions