PHP / PHP Database Integration

Connecting PHP to MySQL with PDO

In this tutorial, you will learn how to use the PHP Data Objects (PDO) interface to connect your PHP application to a MySQL database.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Introduces connecting PHP with databases using MySQL and PDO.

1. Introduction

This tutorial will guide you to connect your PHP application to a MySQL database using the PHP Data Objects (PDO) interface. PDO is a database access layer providing a uniform method of access to multiple databases.

By the end of this tutorial, you will be able to:

  • Understand the basics of PDO and how it interacts with MySQL
  • Establish a connection to MySQL database using PDO
  • Execute basic SQL queries using PDO

Prerequisites:
* Basic understanding of PHP and MySQL
* PHP and MySQL installed on your machine
* A MySQL database to connect to

2. Step-by-Step Guide

2.1 Understanding PDO

PDO provides a consistent interface for accessing databases in PHP. It supports 12 different database systems, of which MySQL is one. PDO is secure and provides an easy way to handle errors.

2.2 Connecting to the Database

To connect to a MySQL database with PDO, you need to instantiate the PDO class. The constructor takes four parameters: DSN (data source name), username, password, and an optional array of driver-specific connection options.

The DSN for MySQL takes the following form:
mysql:host=hostname;dbname=databasename

Here is a basic example of a PDO connection:

<?php
$host = 'localhost';
$db   = 'testdb';
$user = 'testuser';
$pass = 'testpass';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
?>

3. Code Examples

3.1 Querying the Database

Here is an example of running a SELECT query with PDO:

<?php
$sql = "SELECT * FROM users";
$stmt = $pdo->query($sql);

while ($row = $stmt->fetch())
{
    echo $row['name'] . "\n";
}
?>

This code will output the name of every user in the "users" table.

3.2 Inserting Data

You can also use PDO to insert data into the database:

<?php
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute(['name' => 'John', 'email' => 'john@example.com']);
?>

This code will insert a new row into the "users" table.

4. Summary

We've learned how to use PDO to connect to a MySQL database from a PHP application. We've also seen how to execute SELECT and INSERT queries.

Next, you could learn more about PDO's capabilities, such as updating and deleting data, preparing statements, and handling errors.

Additional resources:
* PHP Documentation on PDO
* PHP The Right Way - Databases

5. Practice Exercises

  1. Write a PHP script to connect to a MySQL database and select all rows from a table.
  2. Modify the above script to insert a new row into the table.
  3. Advanced: Create a simple web form that inserts data into a MySQL database using PDO.

Solutions will vary based on your specific database schema. Remember to use prepared statements to protect against SQL injection attacks. Practice with different SQL queries to get a feel for how PDO works.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help