By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,913 Members | 1,274 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Object Oriented mysqli connection function

PsychoCoder
Expert Mod 100+
P: 465
Recently a friend was having a hard time connecting using mysqli, so I showed an OO way of accomplishing the task with this code

Expand|Select|Wrap|Line Numbers
  1. class db_connection extends mysqli 
  2. {
  3.     public function __construct($dbhost, $username, $password, $db) 
  4.     {
  5.         parent::__construct($dbhost, $username, $password, $db);
  6.  
  7.         if (mysqli_connect_error()) 
  8.         {
  9.             die('Connection Error: (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
  10.         }
  11.     }
  12. }
  13.  
  14. $db = new db_connection('localhost', 'username', 'password', 'db');
  15.  
  16. echo 'Success... ' . $db->mysqli_get_host_info($db) . "\n";
  17.  
  18. $db->close();
Jan 10 '12 #1
Share this Article
Share on Google+
1 Comment


Dormilich
Expert Mod 5K+
P: 8,639
if it is not required to use MySQLi, I recommend to use PDO. if that has a connection problem, a PDOException is thrown automatically (and you can set PDO to use Exceptions for every error it encounters).
Jan 18 '12 #2