PHP MySQL: Making a connection to MySQL OOP Style

First, start the WAMP server so that Apache and MySQL servers are started.

If you have removed the allartist database in MySQL, you can create it again using phpMyAdmin.


$mysqli = new mysqli("localhost", "root", "", "allartist");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL";
echo $mysqli->host_info . "<br>";

$mysqli = new mysqli("", "root", "", "allartist", 3306);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL";

echo $mysqli->host_info . "<br>";

Since we have installed WAMP on the local PC, we can use localhost or  Notice we have passed the connection to a variable $mysqli.

With this variable $mysqli, we can print out the host info using $mysqli->host_info.

When we run the above script, the output is as below.  It is basically how the script accesses the MySQL database allartist through TCP/IP protocol.

localhost via TCP/IP via TCP/IP


Object Oriented Style (OOP)

In OOP style, we have used new to create an object.  In OOP, a variable is treated as an object and so we can assign the object to $mysql.

In PHP, the -> is a referencing method. Other languages use a dot for this operator.

PHP couldn’t as PHP is using dot for string concat, hence the -> instead.

Series Navigation<< PHP MySQL: Introduction
PHP MySQL: Making connection to DB non OOP procecural style >>

2 thoughts on “PHP MySQL: Making a connection to MySQL OOP Style

  1. Sorry but… why don’t you use PDO? it’s more safe than MySQLI… it’s my opinion…

    1. I thought it’s better to use mysqli now. PDO is not supported in some later versions of PHP.

Comments are closed.