Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.