Jump to content

Mysqli singleton class


ftm

Recommended Posts

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();
?>
Link to comment
https://forums.phpfreaks.com/topic/293664-mysqli-singleton-class/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.