How to Connect a MySQL Database with PHP

If you want to fetch information from database or insert information to a database using PHP, first you need to establish a connection between MySQL database and PHP. You can easily manipulate databases from your PHP scripts once you have connected them.

Here  I will show you, how you can connect your MySQL database with your PHP scripts.

There are two ways of doing this.

  • MySQLi
  • PDO(PHP Data Object).

PDO can connect with 12 types of databases while MySQLi only works with MySQL databases. If I were you, I would choose PDO. Because if you switch your project to any other databases in future, you can easily work with that altering your existing PDO connection.

PDO extension is object oriented based while MySQLi works both object oriented way and procedural way. Let’s check out how to connect MySQL databases with PHP using PDO and MySQLi extensions.

Connect MySQL Database with PHP using MySQLi

I mentioned before that we can use MySQLi both procedural way and Object Oriented way. First, let’s check the procedural way first.

We stored the parameters on variables. These parameters are servername, username and password. If you’re practicing on a local server, by default these values are localhost, root; password is blank by default.

And then we use mysqli_connect() function to connect the database.

Now, let’s check the Object Oriented way of using MySQLi.

Here, $connection is our MySQLi Object that we can reference to when we want to query the database. mysqli_connect_error() function is used to show any error if database connection fails.

Connect MySQL database with PHP using PDO

Now let’s check PDO or PHP Object Data way to connect our databases with PHP. Unlike MySQLi, PDO also requires the database name to which you want to connect.

Here I used the try…catch which is similar to if…else statements. Notice, how I mentioned the Database name to which I am connecting.

$connect is our PDO object that we’ll reference to when we want to query the database.  PDOExceptions shows errors raised by PDO.

I hope now you can easily connect your databases with PHP.

Let me know through comments if you have any questions.

Sharing is Caring
Check Out These Too
No related posts for this content
Imtiaz Rayhan

WordPress Enthusiast, Novice PHP Developer. Music Addict, The Beatles Fan. Conncect with me on Facebook, Google+ and Twitter.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: