Object Oriented mysqli connection function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PsychoCoder
    Recognized Expert Contributor
    • Jul 2010
    • 465

    #1

    Object Oriented mysqli connection function

    Recently a friend was having a hard time connecting using mysqli, so I showed an OO way of accomplishing the task with this code

    Code:
    class db_connection extends mysqli 
    {
        public function __construct($dbhost, $username, $password, $db) 
    	{
            parent::__construct($dbhost, $username, $password, $db);
    
            if (mysqli_connect_error()) 
    		{
                die('Connection Error: (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
            }
        }
    }
    
    $db = new db_connection('localhost', 'username', 'password', 'db');
    
    echo 'Success... ' . $db->mysqli_get_host_info($db) . "\n";
    
    $db->close();
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    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).

    Comment

    Working...