php - OOP MySQLi Connect -


im newbie in oop. have class database

class database{ private $host; private $user; private $pass; private $db; public $mysqli;  function db_connect(){     $this->host = 'localhost';     $this->user = 'root';     $this->pass = '';     $this->db = 'db';      $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);     return $this->mysqli; } 

inside class database have function db_num

function db_num($sql){     $num = mysqli_num_rows(mysqli_query($this->mysqli,"{$sql}"));     return $num; } 

but cant connect database when im using in con argument $this->mysqli

it bad practice mix mysqli object style , procedural style.

try this:

function db_num($sql){     $result = $this->mysqli->query($sql);     return $result->num_rows; } 

be sure connect database before call db_num(), e.g.:

$db = new database(); $db->db_connect(); $db->db_num("select fields yourtable"); 

a cleaner way in opinion call db_connect inside constructor:

class database{   private $host;   private $user;   private $pass;   private $db;   public $mysqli;    public function __construct() {     $this->db_connect();   }    private function db_connect(){     $this->host = 'localhost';     $this->user = 'root';     $this->pass = '';     $this->db = 'db';      $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);     return $this->mysqli;   }    public function db_num($sql){         $result = $this->mysqli->query($sql);         return $result->num_rows;   } }  $db = new database(); $db->db_num("select fields yourtable"); 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -