ftm Posted January 4, 2015 Share Posted January 4, 2015 Hi, i made a singleton class to make connecting to the db easyer. I got some questions. 1: is this the right way i wrote this class? 2: how can i easy implement mysqli prepare in this class? I've looked everywhere but prepared staments need more lines of code to make it work and i don't know how to implement that in the singleton class. <?php require_once(dirname(dirname(__FILE__)) . "/config.php"); class Database { public static $instance; private $mysqli, $query, $results, $count = 0; public static function getInstance() { if (!self::$instance) { self::$instance = new Database(); } return self::$instance; } public function __construct() { $this->mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE); if ($this->mysqli->connect_error) { die($this->mysqli->connect_error); } } public function query($sql) { if ($this->query = $this->mysqli->query($sql)) { while ($row = $this->query->fetch_assoc()) { $this->results[] = $row; } $this->count = $this->query->num_rows; } return $this; } public function results() { return $this->results; } public function count() { return $this->count; } } ?> usage: <?php include('database.php'); $r = Database::getInstance()->query('SELECT * FROM users'); foreach ($r->results() as $row) { echo $row['name'] . '</br>'; } echo $r->count(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/293664-mysqli-singleton-class/ Share on other sites More sharing options...
Jacques1 Posted January 5, 2015 Share Posted January 5, 2015 What's the whole point of this class? It seems to be a lot of code for very little functionality. If you're looking for database abstraction and convenience, PDO is the way to go. I wonder why people use MySQLi at all. Quote Link to comment https://forums.phpfreaks.com/topic/293664-mysqli-singleton-class/#findComment-1501779 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.