Running SQL Queries from PHP: A Beginner’s Guide

Running SQL Queries from PHP: A Beginner’s Guide

If you’re building dynamic websites or web applications with PHP, running SQL queries from PHP is a skill you must master. Whether you’re pulling data from a database, inserting user input, or updating records, SQL and PHP work hand-in-hand to bring your app to life.

In this guide, we’ll walk you through everything you need to know — from connecting to a MySQL database, writing SQL queries, and executing them using both MySQLi and PDO. Don’t worry if you’re just starting out — we’ll take it step by step and include easy-to-follow code snippets to help you along the way.

Why Run SQL Queries from PHP?

Before diving into code, let’s understand why this is important:

  • PHP is a server-side scripting language.
  • SQL (Structured Query Language) is used to interact with databases.
  • Together, they allow you to store, retrieve, and manage data dynamically on your website.

Common use cases:

  • Displaying blog posts or products
  • User authentication (login/register)
  • Managing orders, feedback, or any data from a form

Prerequisites

To follow along, make sure you have:

  • A local server (like XAMPP, WAMP, or MAMP)
  • PHP installed (usually bundled in the local server)
  • MySQL running
  • A basic understanding of HTML and PHP

Creating a Sample Database and Table

Let’s create a simple database and table to run queries against.

SQL
CREATE DATABASE my_app;

USE my_app;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Connecting to MySQL from PHP

Method 1: Using MySQLi

PHP
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'my_app';

// Create connection
$conn = new mysqli($host, $username, $password, $database);

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

Method 2: Using PDO

PHP
<?php
$dsn = 'mysql:host=localhost;dbname=my_app';
$username = 'root';
$password = '';

try {
    $pdo = new PDO($dsn, $username, $password);
    echo "Connected successfully!";
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}
?>

✅ Tip: PDO supports multiple database types, while MySQLi only supports MySQL. Choose PDO for flexibility.

Running SQL Queries from PHP Using MySQLi

1. SELECT Query (Read Data)

PHP
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}

2. INSERT Query (Create Data)

PHP
$name = "John Doe";
$email = "john@example.com";

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $conn->error;
}

⚠️ Note: Avoid directly inserting user input into queries — it exposes your app to SQL injection.

Using Prepared Statements in MySQLi (Secure Way)

PHP
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

$name = "Alice";
$email = "alice@example.com";
$stmt->execute();

echo "Record inserted securely!";

Running SQL Queries from PHP Using PDO

1. SELECT Query

PHP
$stmt = $pdo->query("SELECT * FROM users");

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

2. INSERT Query with Prepared Statements

PHP
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);

$stmt->execute([
    ':name' => 'Bob Smith',
    ':email' => 'bob@example.com'
]);

echo "Record inserted using PDO!";

💡 Tip: PDO’s named placeholders make the code cleaner and easier to maintain.

Updating and Deleting Records

Update with MySQLi

PHP
$sql = "UPDATE users SET email='new@example.com' WHERE name='John Doe'";
$conn->query($sql);

Delete with PDO

PHP
$sql = "DELETE FROM users WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(['email' => 'bob@example.com']);

Handling Errors Gracefully

Instead of showing raw error messages, log them:

PHP
try {
    // your DB code
} catch (PDOException $e) {
    error_log($e->getMessage());
    echo "Something went wrong. Please try again later.";
}

Best Practices When Running SQL Queries from PHP

  • ✅ Use prepared statements to prevent SQL injection.
  • ✅ Validate and sanitize all user input.
  • ✅ Use PDO if you plan to switch databases later.
  • ✅ Close your database connection when done: phpCopyEdit$conn->close(); // MySQLi $pdo = null; // PDO

Common Mistakes to Avoid

MistakeFix
Hardcoding user input into SQLUse prepared statements
Not checking for connection errorsAlways check with try...catch or connect_error
Mixing HTML with SQL logicKeep your code modular
Ignoring SQL errorsAlways log or display them during development

When to Use MySQLi vs PDO

FeatureMySQLiPDO
MySQL Support✅✅
Other DB support❌✅
Named placeholders❌✅
Object-Oriented✅✅
Easier for beginners✅✅

🎯 Final Thoughts

Learning how to run SQL queries from PHP is a crucial step toward becoming a confident PHP developer. Whether you choose MySQLi for simplicity or PDO for flexibility, the goal is the same: to interact with your database securely and efficiently.

Don’t forget to use prepared statements, handle errors gracefully, and keep your code clean.

Need a refresher on connecting PHP to MySQL? Check out our guide:
👉 How to Connect MySQL Database to PHP: A Complete Beginner’s Guide

For further reading on SQL syntax and commands, we recommend the official MySQL Documentation.

Happy coding! 🎉


Comments

Leave a Reply

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