PHP MySQL: Making a connection to MySQL OOP Style

This entry is part 2 of 17 in the series PHP & MySQL

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

Leave a Reply