Last active
June 20, 2023 08:41
-
-
Save jonashansen229/4534794 to your computer and use it in GitHub Desktop.
PHP OOP Database class using MySQLI and Singleton pattern. Only one instance of the class will be made, this requires less memory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Mysql database class - only one connection alowed | |
*/ | |
class Database { | |
private $_connection; | |
private static $_instance; //The single instance | |
private $_host = "HOSTt"; | |
private $_username = "USERNAME"; | |
private $_password = "PASSWORd"; | |
private $_database = "DATABASE"; | |
/* | |
Get an instance of the Database | |
@return Instance | |
*/ | |
public static function getInstance() { | |
if(!self::$_instance) { // If no instance then make one | |
self::$_instance = new self(); | |
} | |
return self::$_instance; | |
} | |
// Constructor | |
private function __construct() { | |
$this->_connection = new mysqli($this->_host, $this->_username, | |
$this->_password, $this->_database); | |
// Error handling | |
if(mysqli_connect_error()) { | |
trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(), | |
E_USER_ERROR); | |
} | |
} | |
// Magic method clone is empty to prevent duplication of connection | |
private function __clone() { } | |
// Get mysqli connection | |
public function getConnection() { | |
return $this->_connection; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I feel like i should know this stuff already I think i have used it before but right now i have had some time away from coding due to life happening and now i can't seem to get my brain to cooperate with what i am trying to get done,
so I started putting together a simple user system and with a simple connection everything worked fine once i changed to this DB class file and included it simple things became broken and i just can not seem to work it out so my original sql select query was a prepared statement,
$sql = "SELECT * FROM users WHERE username=? AND password=? AND user_type=?"; $stmt = $mysqli->prepare($sql); $stmt->bind_param("sss",$username,$password,$userType); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc();
this was working just fine with the standard inline connection, now with the class file included i get
"Fatal error: Uncaught Error: Call to a member function prepare() on null in /homepages/15/d842734408/htdocs/MURB/index.php:22 Stack trace: #0 {main} thrown in"
can anyone please correct my line of thinking on this so i can move on and remember what i need here please