How to Connect MySQL Database in PHP ? See Example

PHP provides two major ways to connect to a MySQL database:

  1. MySQLi (MySQL Improved Extension)
  2. PDO (PHP Data Objects)

Both methods allow you to run SQL queries, fetch records, insert/update data, and manage the database.
MySQLi is simpler and supports only MySQL, whereas PDO supports 12 different databases like MySQL, PostgreSQL, SQLite, Oracle, etc.


Connecting Using MySQLi (Procedural Style)

Example

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

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

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

echo "Connected successfully!";
?>

Steps Explained:

  • mysqli_connect() → Creates a connection
  • localhost → Server location
  • root → Default MySQL username
  • test_db → Name of the database you want to connect to
  • Program will stop if connection fails (using die())

Connecting Using MySQLi (Object-Oriented Style)

<?php
$conn = new mysqli("localhost", "root", "", "test_db");

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

echo "Connected successfully!";
?>

Connecting Using PDO (Recommended)

PDO is flexible, secure, and supports prepared statements.

Example

<?php
$dsn = "mysql:host=localhost;dbname=test_db";
$username = "root";
$password = "";

try {
    $pdo = new PDO($dsn, $username, $password);

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    echo "Connected successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

Why PDO is better?

  • Database-independent
  • Improved security
  • Easy switching to another database
  • Better error handling
  • Supports advanced features like prepared statements

Testing the Connection

After connecting, you can run a sample query to verify:

$sql = "SELECT * FROM users";

$result = mysqli_query($conn, $sql);

if ($result) {
    echo "Query executed!";
}

or with PDO:

$stmt = $pdo->query("SELECT * FROM users");
foreach ($stmt as $row) {
    print_r($row);
}

Important Notes

Use correct credentials

  • Host → usually localhost
  • Username → root (XAMPP/WAMP default)
  • Password → empty for local servers
  • Database name → must exist

Enable MySQL extension

Make sure extensions are enabled in PHP:

  • extension=mysqli
  • extension=pdo_mysql

Use prepared statements

To prevent SQL Injection.


Common Errors and Fixes

Error: Access denied

Wrong username/password.

Error: Unknown database

Database does not exist or name is incorrect.

Error: Can’t connect to MySQL server

MySQL service may not be running.

Error: Call to undefined function mysqli_connect()

MySQLi extension disabled → enable in php.ini.


Example Folder Structure

project/
 ├── connect.php
 ├── index.php
 └── config/
      └── db.php

Always keep database credentials in a separate config file for security.


Citations

🔗 View other articles about PHP:
http://savanka.com/category/learn/php/

🔗 External PHP Documentation:
https://www.php.net/manual/en/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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