How to Connect MySql Database using PHP – Programming Code Examples

How to Connect MySql Database using PHP2 min read

How to connect MySql database using PHP. PHP provides inbuilt functions to connect to MySql database using their extensions. In this post, I’ll explain how to connect MySql Database using  PHP.

In PHP, you can connect MySql database using following extensions.

1) MySql (Worked only if you are using PHP Version 5.4 or less than that)

2) MySqli (MySql Improved)

3) PDO (PHP Data Objects)

Mysql API extension is deprecated from PHP 5.4 and now this extension is removed from the current version of PHP. So it’s better to learn how to connect MySql database using MySqli and PDO .

PHP Traits

Late static binding in PHP

Advantage of using MySqli and PDO

1. MySqli and PDO both supports parameterized query which is helpful in preventing an application from SQL injection .

2. Both supports object-oriented interface.

3. Accessing database through MySqli and PDO is faster than previously used MySql API extension.

Difference Between MySqli and PDO

How to Connect MySql Database using PHP

To access MySql database in your code, you need to do following steps –

1. Open a connection.

2. Specify and Connect to the database.

3. Once connection is establish, query(Select/Insert/Update) the database.

4. Close the connection.

Connect MySql Database using PHP MySqli

Connect MySql Database using PHP PDO

To prevent an application from SQL injection try to use the prepared statement.

Read detail post on connecting MySQL database using PDO.

Leave a Comment