Skip to content

PHP By Exalogics

A Simple Easy Site to Learn, Understand and create php

Menu
  • Home
  • Welcome to php by Exalogics
    • Introduction to PHP
    • How to Install PHP on Windows
    • PHP Variables
    • PHP Constants
    • PHP Switch Statement
    • PHP Data Types
    • PHP Operators
    • PHP If Else Statements
    • PHP E-Commerce Development
    • Your First PHP Script
    • PHP Error Handling
    • PHP Frameworks Guide
    • PHP MySQL Database Development
    • PHP Security Best Practices
    • PHP CMS Development
    • PHP Hosting Guide
  • PHP API Development
Menu

How Does PHP Connect to a MySQL Database?

Posted on November 26, 2026






How Does PHP Connect to a MySQL Database?


How Does PHP Connect to a MySQL Database?

Connecting PHP to a MySQL database is one of the most common tasks for web developers. Whether you’re building a simple blog or a complex e‑commerce platform, a reliable database connection is the backbone of dynamic content. This article walks you through the two official PHP extensions—MySQLi and PDO (PHP Data Objects)—providing clear code examples, best‑practice tips, and troubleshooting advice.

Why a Proper Database Connection Matters

A well‑structured connection ensures:

  • Secure handling of credentials.
  • Efficient resource usage (persistent vs. non‑persistent connections).
  • Protection against SQL injection through prepared statements.
  • Scalability for larger applications.

Prerequisites Before You Start

Server Requirements

Make sure your environment meets the following:

  • PHP 7.4 or newer (both MySQLi and PDO are built‑in).
  • MySQL 5.7+ or MariaDB 10.2+.
  • Correct php.ini settings for the extensions (they are enabled by default).

Gather Connection Details

Typical connection parameters you’ll need:

Parameter Example
Host localhost
Port 3306
Database name my_database
Username db_user
Password secure_password

Connecting with MySQLi

The MySQLi (MySQL Improved) extension offers both procedural and object‑oriented APIs. Below are the most common patterns.

Object‑Oriented Example


$host = 'localhost';
$user = 'db_user';
$pass = 'secure_password';
$db   = 'my_database';
$port = 3306;

$mysqli = new mysqli($host, $user, $pass, $db, $port);

if ($mysqli->connect_error) {
    die('Connection error (' . $mysqli->connect_errno . ') '
        . $mysqli->connect_error);
}

// Set character set to UTF‑8
$mysqli->set_charset('utf8mb4');

Procedural Example


$mysqli = mysqli_connect($host, $user, $pass, $db, $port);

if (!$mysqli) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
}

mysqli_set_charset($mysqli, 'utf8mb4');

Using Prepared Statements (MySQLi)


$stmt = $mysqli->prepare('SELECT id, name FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    echo $row['name'];
}
$stmt->close();

Connecting with PDO

PDO provides a consistent interface for many databases (MySQL, PostgreSQL, SQLite, etc.). It is the preferred choice when you might switch DBMS later.

Basic PDO Connection


$dsn = 'mysql:host=localhost;dbname=my_database;charset=utf8mb4';
$user = 'db_user';
$pass = 'secure_password';

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, // Throw exceptions on errors
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,       // Fetch associative arrays
    PDO::ATTR_EMULATE_PREPARES   => false,                  // Use native prepares if possible
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

Prepared Statements with PDO


$sql = 'SELECT id, name FROM users WHERE email = :email';
$stmt = $pdo->prepare($sql);
$stmt->execute(['email' => $email]);

foreach ($stmt as $row) {
    echo $row['name'];
}

Best Practices for Secure Connections

  • Never hard‑code credentials in source files that are part of version control. Use environment variables or a secure configuration file outside the web root.
  • Enable PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION (or mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT)) to catch errors early.
  • Always use prepared statements or parameterized queries to prevent SQL injection.
  • Set the character set to utf8mb4 to fully support Unicode, including emojis.
  • Consider persistent connections (PDO::ATTR_PERSISTENT => true) only after benchmarking, as they can consume server resources.

Common Connection Errors & How to Fix Them

Error Message Typical Cause Solution
Access denied for user ‘user’@’localhost’ Wrong username/password or missing privileges Verify credentials, grant necessary privileges, and check host restrictions.
SQLSTATE[HY000] [2002] Connection timed out Incorrect host/port or firewall blocking Confirm host address, open MySQL port in firewall, and ensure MySQL is listening.
PDOException: could not find driver PDO MySQL driver not installed Install the php-pdo_mysql extension and restart the web server.

Testing the Connection

After establishing the connection, a quick test query can confirm everything works:


// Using PDO
$stmt = $pdo->query('SELECT VERSION()');
echo 'MySQL version: ' . $stmt->fetchColumn();

Conclusion

PHP offers two robust ways to connect to MySQL: MySQLi for MySQL‑specific features and PDO for a database‑agnostic approach. By following the examples and best practices above, you’ll create secure, maintainable, and high‑performance database connections that scale with your application.


Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Can PHP Connect to SQL Server?
  • How Does PHP Connect to a MySQL Database?
  • Bangkok 4-Day City Guide: Temples, Floating Markets, & Shopping Malls
  • What Are PHP and MySQL?
  • PHP, Databases & JSON – A Comprehensive Guide

Recent Comments

  1. How to Concatenate Strings in PHP - 93 Travellers Pakistan on How to Concatenate Strings in PHP
  2. What Does trim() Do in PHP? - 93 Travellers Pakistan on What Does trim() Do in PHP?
  3. PHP String Functions: A Complete Reference - 93 Travellers Pakistan on PHP String Functions: A Complete Reference
  4. What Does implode() Do in PHP? - 93 Travellers Pakistan on What Does implode() Do in PHP?
  5. What Does explode() Do in PHP? - 93 Travellers Pakistan on What Does explode() Do in PHP?

Archives

  • November 2026
  • October 2026
  • September 2026
  • August 2026
  • July 2026

Categories

  • PHP Basics
  • Uncategorized
©2026 PHP By Exalogics | Design: Newspaperly WordPress Theme