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.

phpmyadmin_createdb

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

$mysqli = new mysqli("127.0.0.1", "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 127.0.0.1.  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
127.0.0.1 via TCP/IP

phpmyadmin_createdb2

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