PHP Basics
Functions in PHP
Working with Forms
Working with Files
Working with Databases
Advanced PHP Techniques

Connecting to a MySQL database using PHP involves several steps. Below, Here is describe the process in detail:

1. Install PHP and MySQL

Ensure you have both PHP and MySQL installed on your server. If you’re using a local development environment like XAMPP, WAMP, or MAMP, these will come pre-installed.

2. Create a Database

Before connecting, you need a MySQL database. You can create one using phpMyAdmin or MySQL command line.

				
					CREATE DATABASE my_database;

				
			

3. Create a User and Grant Permissions

Create a MySQL user and grant them the necessary permissions to the database.

				
					CREATE USER 'my_user'@'localhost' IDENTIFIED BY 'my_password';
GRANT ALL PRIVILEGES ON my_database.* TO 'my_user'@'localhost';
FLUSH PRIVILEGES;

				
			

4. Connect to MySQL using PHP

You can connect to MySQL using PHP in two main ways: ‘mysqli‘ extension and ‘PDO‘ (PHP Data Objects).

Using mysqli Extension

mysqli is a PHP extension that allows you to access the functionality provided by MySQL.

Procedural Style:

				
					<?php
$servername = "localhost";
$username = "my_user";
$password = "my_password";
$dbname = "my_database";

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

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

// Close the connection
mysqli_close($conn);
?>

				
			

Object-Oriented Style:

				
					<?php
$servername = "localhost";
$username = "my_user";
$password = "my_password";
$dbname = "my_database";

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

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

// Close the connection
$conn->close();
?>

				
			

Using PDO (PHP Data Objects)

PDO is a more flexible and powerful way to interact with databases in PHP, supporting multiple database types.

				
					<?php
$dsn = "mysql:host=localhost;dbname=my_database";
$username = "my_user";
$password = "my_password";

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

// Close the connection
$pdo = null;
?>

				
			

5. Performing Database Operations

Once connected, you can perform various database operations like querying, inserting, updating, and deleting records.

Using mysqli Extension

Example: Fetching Data Using mysqli Procedural Style

				
					<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);

$sql = "SELECT id, name FROM my_table";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>

				
			

Example: Fetching Data Using PDO

				
					<?php
try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $stmt = $pdo->query("SELECT id, name FROM my_table");

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "id: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
    }
}
catch(PDOException $e) {
    echo "Query failed: " . $e->getMessage();
}

$pdo = null;
?>

				
			

6. Handling Errors

It’s important to handle errors gracefully. Both mysqli and PDO provide mechanisms for error handling.

Using mysqli

Procedural Style:

				
					<?php
if (mysqli_connect_errno()) {
    die("Connection failed: " . mysqli_connect_error());
}
?>

				
			

Object-Oriented Style:

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

				
			

Using PDO

				
					<?php
try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>

				
			

7. Security Considerations

  • Use Prepared Statements: To prevent SQL injection, use prepared statements and parameterized queries.
  • Store Credentials Securely: Store database credentials securely, preferably outside the web root directory.
  • Error Handling: Avoid displaying detailed error messages to users.

Example: Prepared Statements with mysqli

				
					<?php
$stmt = $conn->prepare("SELECT id, name FROM my_table WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$stmt->bind_result($id, $name);

while ($stmt->fetch()) {
    echo "id: $id - Name: $name<br>";
}

$stmt->close();
?>

				
			

Example: Prepared Statements with PDO

				
					<?php
$stmt = $pdo->prepare("SELECT id, name FROM my_table WHERE id = :id");
$stmt->bindParam(':id', $id);
$id = 1;
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "id: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
}
?>

				
			

Following these steps will help you establish a secure and efficient connection to a MySQL database using PHP.

Scroll to Top