JcHub
Cheat sheetFree, no sign-upPDF

PHP & MySQL Cheat Sheet: Syntax and Common Queries

Quick reference for PHP PDO database connections, prepared statements, and essential MySQL queries for web applications.

Updated on November 9, 2026

PHP PDO MySQL Connection

  • $pdo = new PDO('mysql:host=localhost;dbname=store_db;charset=utf8mb4', 'user', 'pass');Establishes a secure PDO database connection. Always set utf8mb4 charset to support full UTF-8 encoding properly.
  • $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);Configures PDO to throw exceptions on errors. Essential for catching database issues safely without exposing credentials.
  • $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);Sets default fetch mode to associative arrays. Removes the need to pass PDO::FETCH_ASSOC to every SELECT query.
  • try { $pdo = new PDO(...); } catch (PDOException $e) { die($e->getMessage()); }Catches connection failures safely. In production environments, log error messages internally instead of displaying them.

Prepared Statements with PDO

  • $stmt = $pdo->prepare('SELECT * FROM clients WHERE city = :city');Prepares SQL statement to prevent SQL injection. Never concatenate untrusted user input directly into SQL strings.
  • $stmt->execute(['city' => 'Nairobi']);Executes prepared statement with bound parameters. Array keys must match the exact named placeholders in the query.
  • $client = $stmt->fetch();Fetches a single row from the result set. Returns false if no matching database record was found.
  • $allClients = $stmt->fetchAll();Fetches all matching rows into an array. Watch out for memory usage if your dataset contains thousands of rows.

MySQL Table Structure & Creation

  • CREATE DATABASE shop_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;Creates database using full UTF-8 encoding. Avoid using legacy utf8mb3 which fails to store 4-byte characters.
  • CREATE TABLE payments (id INT AUTO_INCREMENT PRIMARY KEY, amount DECIMAL(10,2), payment_date DATETIME);Creates a payments table. Always use DECIMAL for currency and financial amounts instead of FLOAT or DOUBLE.
  • ALTER TABLE clients ADD COLUMN phone VARCHAR(20) AFTER email;Adds a new column after a specific field. Check whether the column already exists before executing migrations.
  • DROP TABLE IF EXISTS sessions;Deletes table without throwing an error if it does not exist. Permanent operation, use with extreme care.

Common MySQL Queries

  • INSERT INTO orders (client_id, total) VALUES (12, 15000.00);Inserts a new record into the table. Retrieve the newly generated auto-increment ID in PHP using $pdo->lastInsertId().
  • SELECT * FROM products WHERE name LIKE '%orange%' ORDER BY price DESC LIMIT 10;Performs a wildcard search with sorting. Leading wildcards '%' prevent MySQL from utilizing table indexes efficiently.
  • UPDATE users SET status = 'active' WHERE last_login >= '2025-01-01';Updates targeted database records. Common trap: omitting the WHERE clause will update every row in the entire table.
  • DELETE FROM carts WHERE created_at < NOW() - INTERVAL 7 DAY;Deletes expired records. Test the criteria using a matching SELECT query first to avoid accidental data loss.
  • SELECT c.name, p.amount FROM clients c INNER JOIN payments p ON c.id = p.client_id;Combines records from two related tables. Ensure foreign key columns are indexed properly for optimal performance.

Security & Useful PHP Functions

  • $hash = password_hash($password, PASSWORD_DEFAULT);Hashes user passwords using strong algorithms. Never store plain text passwords or use outdated MD5 or SHA1 hashes.
  • if (password_verify($input, $hashFromDb)) { /* Valid */ }Verifies if input password matches the stored database hash. Automatically handles internal salt verification.
  • $clean = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');Sanitizes database outputs before rendering them inside HTML pages. Essential protection against XSS vulnerabilities.
  • $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);Validates email format natively in PHP. Returns false if invalid before attempting database insertion or storage.

Other resources

Need help with your website?

I build your custom website.

Showcase site, online shop, management tool: let’s talk about your project.

See the services