0

i have witten this php class, but i have problem using it,

<?php
    class cs_mysql{
        protected $configPath;
        protected $db;
        function __construct($cP = null){
            $this->configPath = $cP;
            require $this->configPath;
        }
        private function connection(){
            $db = new mysqli(Config::get('dbHost'),Config::get('dbUser'),Config::get('dbPass'),Config::get('dbName'));
        }
        public function getRow($table){
            $query = 'SELECT * FROM $table ORDER BY `id` DESC';
            $sql = $this->db->query($query);
            if(!$sql){
                echo "FALSE";
            }
        }
    }
?>

i don't know how to run db query : $sql = $this->db->query($query);

1 Answers1

0

Change

$db = new mysqli(Config::get('dbHost'),Config::get('dbUser'),Config::get('dbPass'),Config::get('dbName'));

to

$this->db = new mysqli(Config::get('dbHost'),Config::get('dbUser'),Config::get('dbPass'),Config::get('dbName'));

$db is a property of the class. To access class properties (and methods) you have to reference the class instance using $this.

DFriend
  • 8,869
  • 1
  • 13
  • 26
  • i got this Error : Fatal error: Uncaught Error: Call to a member function query() on null in /Applications/XAMPP/xamppfiles/htdocs/bonbegir/bbadmin/classes/mysql.class.php:14 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/bonbegir/index.php(7): cs_mysql->getRow('category') #1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/bonbegir/bbadmin/classes/mysql.class.php on line 14 – Amir Mohammad Rivand Oct 25 '16 at 19:10
  • @AmirMohammadRivand as I mentioned in my comment to your question, you are not calling `connection()` anywhere so `$this->db` will be null. You should call `$this->connection()` before you do `$this->db->query()` – Cave Johnson Oct 25 '16 at 19:19