PHP 3d ago 5 views 1 min read

How to use PHP PDO to execute raw SQL queries

Connect to a MySQL database using PDO, execute raw SQL strings, and fetch results safely. This guide covers configuration, execution methods, and error handling for PHP 8.3.

Riya K.
Updated 18h ago
Sponsored

Cloud VPS — scale in minutes

Instantly deploy SSD cloud VPS with guaranteed resources, snapshots and per-hour billing. Pay only for what you use.

You will configure a PHP PDO connection to execute raw SQL queries and fetch results from a MySQL database. These steps target PHP 8.3.x and MySQL 8.0.x on Ubuntu 24.04. You will learn to use exec(), query(), and prepare() methods to run statements.

Prerequisites

  • Ubuntu 24.04 or Debian 12 with PHP 8.3.x installed.
  • A running MySQL or MariaDB server.
  • A database and table created beforehand.
  • PHP PDO extension enabled (php -m | grep pdo).
  • Write permissions for the database user.

Step 1: Create a database and table

Create a test database and a table named users with an id and name column. This provides a target for your raw SQL queries.

mysql -u root -p -e "
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);
INSERT INTO users (name) VALUES ('Alice'), ('Bob'), ('Charlie');
"

Expected output shows the table created and rows inserted:

Database created.
Table created.
3 rows affected.

Step 2: Create the PDO connection

Define a function to create a PDO instance using a DSN string, username, and password. This centralizes connection logic and handles exceptions.

      
Sponsored

Windows Dedicated Server

High-performance Windows dedicated servers with licensed Windows Server, Remote Desktop access and enterprise-grade hardware.

Tags: phppdoSQLDatabases
0
Was this helpful?

Related tutorials

Comments 0

Login to leave a comment.

No comments yet — be the first to share your thoughts.