global $db
I heard thats not the best practice though ? Can anyone give my brief explanation why ? And If that's true what is better practice then?
thanks in advance




Posted 18 March 2013 - 12:38 PM
global $db
Posted 18 March 2013 - 01:38 PM
<?php
class DB
{
private static $instance; // stores the MySQLi instance
private function __construct() { } // block directly instantiating
private function __clone() { } // block cloning of the object
public static function get() {
// create the instance if it does not exist
if(!isset(self::$instance)) {
// the MYSQL_* constants should be set to or
// replaced with your db connection details
self::$instance = new MySQLi(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
if(self::$instance->connect_error) {
throw new Exception('MySQL connection failed: ' . self::$instance->connect_error);
}
}
// return the instance
return self::$instance;
}
}
?>
$result = DB::get()->query("SELECT * FROM ...");
Posted 18 March 2013 - 04:29 PM
P.Conrad, on 18 March 2013 - 04:12 PM, said:
Quote
Posted 19 March 2013 - 03:21 AM
Posted 19 March 2013 - 06:08 AM
$db = self::$db;or in every method which needs connection reference to our singleton ?
private function(){ $db = DB::get(); ...
Posted 19 March 2013 - 11:03 AM
P.Conrad, on 19 March 2013 - 06:08 AM, said:
$db = self::$db;or in every method which needs connection reference to our singleton ?
private function(){ $db = DB::get(); ...
Posted 19 March 2013 - 06:51 PM
$result = DB::get()->query("SELECT * FROM ...");
This post has been edited by CTphpnwb: 19 March 2013 - 06:57 PM
Posted 20 March 2013 - 05:19 AM
if(isset($_POST['nick']) && isset($_POST['pass']))
{
$stmt = DB::get() -> prepare("SELECT id_user FROM user where nick = ? and pass = ?");
$stmt -> bind_param("ss", $_POST['nick'], md5($_POST['pass']));
$result = $stmt -> execute();
if($result -> num_rows > 0) // good login and pass
else // bad login and/or pass
Posted 20 March 2013 - 06:51 AM
$stmt = DB::get() -> prepare("SELECT verified FROM user where nick = ? AND pass = ?");
$stmt -> bind_param("ss", $_POST['nick'], md5($_POST['pass']));
$stmt -> execute();
$stmt-> store_result();
$stmt -> bind_result($verified);
$stmt -> fetch();
if($stmt -> num_rows == 0) // bad login and/or pass
elseif($verified == 0) // users not verified
else // users logged properly!
Posted 20 March 2013 - 12:33 PM
Posted 21 March 2013 - 11:12 AM
|
|
Query failed: connection to localhost:3312 failed (errno=111, msg=Connection refused).
|
