How to Connect PHP to MySQL: A Step-by-Step Guide

0
542

Connecting PHP to MySQL is essential for building dynamic web applications that store and manage data efficiently. This guide explains how to establish a connection between PHP and MySQL using both MySQLi (MySQL Improved) and PDO (PHP Data Objects).


1. Prerequisites

Before proceeding, ensure that:
βœ… You have PHP and MySQL installed on your server or local machine (e.g., using XAMPP, WAMP, or MAMP).
βœ… You have created a MySQL database and a user account with appropriate permissions.
βœ… You are familiar with basic PHP syntax.


2. Methods to Connect PHP to MySQL

There are two primary ways to connect PHP to MySQL:

  1. MySQLi (MySQL Improved) Extension – Works only with MySQL databases.
  2. PDO (PHP Data Objects) – Supports multiple database types and is more flexible.

3. Connecting Using MySQLi (Procedural and Object-Oriented)

A. Using MySQLi (Procedural Method)

The procedural approach uses simple function calls.

<?php
$server = "localhost"; // Change to your MySQL server (e.g., 127.0.0.1)
$username = "root";    // MySQL username (default is "root" for local development)
$password = "";        // MySQL password (leave empty if using XAMPP)
$database = "test_db"; // Name of the database

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

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

πŸ‘‰ Explanation:

  • mysqli_connect() establishes a connection.
  • If the connection fails, mysqli_connect_error() displays the error.
  • If successful, "Connected successfully" is displayed.

B. Using MySQLi (Object-Oriented Method)

This approach is more structured and preferred for larger projects.

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

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

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

πŸ‘‰ Key Differences:

  • Uses the new mysqli() object.
  • Connection errors are checked using $conn->connect_error.

4. Connecting Using PDO (More Secure & Flexible)

PDO provides a more secure and flexible way to connect to MySQL and other databases.

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

try {
    $conn = new PDO("mysql:host=$server;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();
}
?>

πŸ‘‰ Why Use PDO?
βœ… Supports multiple databases (MySQL, PostgreSQL, SQLite, etc.)
βœ… Uses prepared statements to prevent SQL injection
βœ… Handles errors using try-catch blocks


5. Closing the Connection

While PHP automatically closes connections when a script ends, you can manually close it:

For MySQLi (Procedural)

mysqli_close($conn);

For MySQLi (Object-Oriented)

$conn->close();

For PDO

$conn = null;  // Closes the connection

6. Handling Errors Securely

To prevent exposing database errors to users, use proper error handling:

MySQLi

if (!$conn) {
    error_log("Connection failed: " . mysqli_connect_error());
    die("Database connection issue. Please try again later.");
}

PDO

try {
    $conn = new PDO("mysql:host=$server;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); // Suppresses errors from displaying
} catch(PDOException $e) {
    error_log("Connection failed: " . $e->getMessage());
    die("Database connection issue. Please try again later.");
}

7. Which One Should You Use?

Feature MySQLi PDO
Supports MySQL βœ… βœ…
Supports Multiple Databases ❌ βœ…
Object-Oriented Support βœ… βœ…
Procedural Support βœ… ❌
Prepared Statements βœ… βœ…
More Secure βœ… βœ… (Better)

Recommendation:

  • Use MySQLi if working only with MySQL and prefer a simple approach.
  • Use PDO for better security, flexibility, and support for multiple databases.

8. Testing the Connection

To verify that your connection works, save the PHP script as connect.php, run it on your server, and open the file in a browser:

http://localhost/connect.php

If successful, you’ll see "Connected successfully". Otherwise, troubleshoot using the error messages.


Final Thoughts

Connecting PHP to MySQL is crucial for database-driven applications. Choosing between MySQLi and PDO depends on your project’s requirements, but PDO is the best choice for security and flexibility.

Would you like guidance on performing CRUD (Create, Read, Update, Delete) operations after connecting? 

Search
Categories
Read More
JavaScript
What to do When working with the DOM
When working with the DOM (Document Object Model) in JavaScript, you're essentially interacting...
By flowisetech 2025-02-03 17:34:36 0 760
PHP
Steps to Create a custom WordPress blog theme
Creating a custom WordPress blog theme requires structuring your files properly and coding them...
By flowisetech 2025-02-21 12:19:06 0 551
HTML
Introduction To HTML
HTML (HyperText Markup Language) is the standard language used to create and design webpages. It...
By Nicholas 2025-01-13 12:52:35 0 1K
YouTube
YouTube Channel Growth Strategies: How to Gain More Subscribers & Views
Growing a YouTube channel requires more than just uploading videosβ€”it takes strategy,...
By flowisetech 2025-02-24 08:19:10 0 418
HTML
How to create advance button in HTML, CSS And JavaScript
Creating an advanced button in HTML involves using HTML, CSS, and optionally JavaScript for...
By Motivegist 2025-03-06 21:54:53 0 500
Flowise Tech https://flowisetech.com