Table of contents
1.
Introduction
2.
What is MySQL?
2.1.
Key Features of MySQL
3.
Downloading MySQL Database
4.
How to Connect PHP with MySQL Database?
5.
Difference Between MySQLi and PDO
5.1.
Connecting to MySQL Database Using PHP
5.1.1.
Using MySQLi (Procedural)
5.1.2.
Using MySQLi (Object-Oriented)
5.1.3.
Using PDO
5.1.4.
Closing a Connection
5.1.4.1.
MySQLi (Procedural)
5.1.4.2.
MySQLi (Object-Oriented)
5.1.4.3.
PDO
6.
Frequently Asked Questions
6.1.
What is the difference between MySQLi and PDO? 
6.2.
How do I check if my PHP code is successfully connected to MySQL? 
6.3.
Is it necessary to close the database connection? 
7.
Conclusion
Last Updated: Jan 18, 2025
Easy

PHP: MySQL Database

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

PHP and MySQL are a popular combination for building dynamic and interactive web applications. PHP is a server-side scripting language that works seamlessly with MySQL, a powerful and easy-to-use database management system. Together, they allow developers to store, retrieve, and manage data efficiently, making them ideal for creating websites like blogs, e-commerce platforms, and content management systems.

PHP: MySQL Database

In this article, we will discuss the basics of MySQL, how to connect it with PHP, and the essential concepts you need to get started.

What is MySQL?

MySQL is an open-source relational database management system (RDBMS) that uses structured query language (SQL) to manage data. It organizes data into tables consisting of rows and columns, making it easy to retrieve and manipulate data efficiently. MySQL is widely used in web development for tasks like user authentication, storing product information, and handling customer orders.

Key Features of MySQL

  • High performance and scalability
     
  • Cross-platform support
     
  • Secure and reliable
     
  • Open-source with a large community of developers
     

Example: Suppose you have an e-commerce website. MySQL can store information about users, products, and orders in structured tables, allowing quick access and updates as needed.

Downloading MySQL Database

To use MySQL on your system, you first need to download and install it. Follow these simple steps:

Visit the Official Website
Go to the MySQL official website to download MySQL.

Choose the Installer
Select the installer suitable for your operating system (Windows, macOS, or Linux).

Install MySQL
Run the installer and follow the steps in the setup wizard. Choose a server configuration that fits your requirements.

Set Up a Root Password
During installation, create a strong root password to secure your database.

Verify Installation
Open the MySQL Command Line Client or Workbench and log in using your root password.

After installation, you are all set to create, manage, and interact with your databases.

How to Connect PHP with MySQL Database?

To connect PHP with MySQL, you need to use one of the two main extensions provided by PHP: MySQLi (MySQL Improved) or PDO (PHP Data Objects). Both allow you to interact with MySQL databases, but they have differences in functionality.

Difference Between MySQLi and PDO

ParametersMySQLiPDO
Database SupportWorks only with MySQLSupports multiple databases
Object-OrientedYesYes
ProceduralYesNo
Named ParametersNoYes
Ease of MigrationDifficultEasy

If your project is specific to MySQL, you can use MySQLi. However, if you may need to switch databases in the future, PDO is the better choice.

There Are Three Ways of Working with MySQL and PHP

  1. MySQLi (Object-Oriented): Allows object-oriented interactions with MySQL databases.
     
  2. MySQLi (Procedural): Offers procedural methods to interact with MySQL.
     
  3. PDO: A more flexible approach, supporting multiple databases.

Connecting to MySQL Database Using PHP

Using MySQLi (Procedural)

<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
$database = "test_db";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";
?>


Explanation:

  • mysqli_connect() establishes the connection.
     
  • The if statement checks if the connection is successful.
     
  • If successful, the script outputs "Connected successfully."

Using MySQLi (Object-Oriented)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";
?>


Explanation:

  • Uses the new mysqli object to create the connection.
     
  • The $conn->connect_error property checks for errors.

Using PDO

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test_db";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    // Set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Explanation:

  • The try block attempts to establish the connection.
     
  • The catch block handles exceptions, showing an error message if the connection fails.

Closing a Connection

Closing a database connection is crucial to free up resources. Use the following commands for each method:

MySQLi (Procedural)
mysqli_close($conn);
MySQLi (Object-Oriented)
$conn->close();
PDO
$conn = null;

Note: In PDO, setting the connection object to null closes the connection.

Frequently Asked Questions

What is the difference between MySQLi and PDO? 

MySQLi works only with MySQL databases, while PDO supports multiple database types and offers better flexibility.

How do I check if my PHP code is successfully connected to MySQL? 

Use conditional checks like mysqli_connect_error() or try-catch blocks with PDO to confirm the connection.

Is it necessary to close the database connection? 

Yes, closing the connection ensures that resources are freed, preventing potential memory leaks.

Conclusion

In this article, we discussed how to work with MySQL databases using PHP, MySQL’s features, installation steps, and how to connect PHP with MySQL using MySQLi and PDO. Practical examples were covered to understand the connection process, ensuring you’re ready to start building your own dynamic web applications. 

Live masterclass