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

0
539

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? 

Rechercher
Catégories
Lire la suite
HTML
Introduction To HTML
HTML (HyperText Markup Language) is the standard language used to create and design webpages. It...
Par Nicholas 2025-01-13 12:52:35 0 1KB
Make Money
How To Make At Least ₦2,000 Daily In Nigeria
Making at least ₦2,000 daily in Nigeria is very achievable, especially with consistency and the...
Par flowisetech 2025-04-21 07:10:15 0 148
Smart Contracts
How Smart Contracts Work: The Backbone of Decentralized Apps
Smart contracts are self-executing contracts with the terms of the agreement directly written...
Par flowisetech 2025-02-25 13:32:55 0 428
Blogging
Eating Like a Local: My Favorite Grocery Stores in Richmond
During my recent stay in Richmond, I stumbled upon something a bit unexpected—my love for...
Par bakulhape 2025-05-01 09:07:10 0 69
JavaScript
How to Create a Flickity Slider in JavaScript with Thumbnail Navigation
Flickity is a popular JavaScript library for creating responsive and touch-friendly sliders. It...
Par flowisetech 2025-02-18 14:56:26 0 548
Flowise Tech https://flowisetech.com