Creating a MySQL Connection Using PHP

PHP/MySQL is one of the most common stacks for web development. To be able to get data from a MySQL database or put data into a MySQL database you must first create a connection from inside your PHP script to your MySQL database. There are 3 main ways to do this: Procedural MySQLi (mysqli_connect), Object Oriented MySQLi (mysqli) and PDO.

Note: I will not be considering the security perspective of creating a connection or running a query using that connection in this post. It will be just the basics of connection creation. Security perspective is to be explained in a later post. Just observe the simple examples below and you should understand how to create MySQL connections using PHP and their differences easily.

Creating a MySQL Connection Using PHP – Object Oriented MySQLi

Creating a MySQL Connection Using PHP – Procedural MySQLi

Creating a MySQL Connection Using PHP – PDO Way


Closing the Connections

The link to the server will be closed as soon as the execution of the script ends, unless it’s closed earlier explicitly. If your script has a fair amount of processing to perform after fetching the result and has retrieved the full result set, you should close the connection. Below are how you can close the connections in different methods.

MySQLi Object Oriented: $conn->close();

MySQLi Procedural: mysqli_close($conn);

PDO: $conn = null;

Hope this helps.
Good Luck,

Leave a Reply

Your email address will not be published. Required fields are marked *