New Page  |  Edit Page

MySQLi - Object Orientated

The following is considered up to date with PHP 8.1. Wrappers and common practices found elsewhere should be considered wrong practice.

CONNECT


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($host, $username, $password, $database, $port);
$mysqli->set_charset($charset);
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);

Connect to the Database

$mysqli->close;

Close the connection to the Database

Class Connect


class MySQL {

    protected $host;
    protected $user;
    protected $password;
    protected $database;
    protected $charset;
    protected $mysqli;

    public function __construct() {
    
        $this->host = "localhost";
        $this->user = "demo";
        $this->password = "1234";
        $this->database = "database";
        $this->charset = "utf8mb4";

        try {
        
            $mysqli = new mysqli($this->host, $this->user, $this->password);
            $mysqli->select_db($this->database);
            $mysqli->set_charset($this->charset);
            $mysqli->report_mode = MYSQLI_REPORT_STRICT | MYSQLI_REPORT_ERROR;
            $mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
        
        }
        
        catch (Exception $e) {
        
            echo 'Error:' . $e->getMessage();
            exit;
            
        }

        $this->mysqli = $mysqli;
    }

}


Connect to the Database as a Class