Code Snippets

PDO MySQL Connection in PHP

PHP

Connect to MySQL with PDO and run a prepared SELECT.

<?php
declare(strict_types=1);

$pdo = new PDO(
    'mysql:host=localhost;dbname=app;charset=utf8mb4',
    'user',
    'pass',
    [
        PDO::ATTR_ERRMODE          => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]
);

$stmt = $pdo->prepare('SELECT id, email FROM users WHERE active = ?');
$stmt->execute([1]);

foreach ($stmt as $row) {
    echo "{$row['id']}\t{$row['email']}\n";
}
Database MysqlPdoSql chris

More in Database

SQLite with the sqlite3 Stdlib Database Create a table, insert rows, and query with parameterized SQL. Connect to PostgreSQL in Go Database Open a database/sql handle to Postgres and query rows. ActiveRecord Query Snippet Database Define a model and run a chained where/order query with ActiveRecord. Connect to MySQL with DBI Database Open a DBI handle to MySQL, run a SELECT, and iterate rows.

Random picks

Install a Cron Job from a Script CLI & System Append a cron line idempotently with grep -q before crontab. CLI Arguments with argparse CLI & System Build a typed CLI parser with the argparse stdlib. Promise.all for Parallel Awaits Concurrency Issue several HTTP requests in parallel with Promise.all. WebSocket Client in the Browser Networking & HTTP Open a WebSocket, send a message, and log incoming frames. ActiveRecord Query Snippet Database Define a model and run a chained where/order query with ActiveRecord.
Recently added
  • Background Jobs and wait
  • Loop SSH Across Hosts
  • Install a Cron Job from a Script
  • Compress a Directory with tar
  • Find Files Recursively
Categories
  • CLI & System 12
  • Concurrency 11
  • Cryptography & Hashing 8
  • Database 5
  • File I/O 21
  • Networking & HTTP 12
  • Sorting & Data Structures 10
  • Strings & Text 11
  • Utilities 16
  • Web Development 6
Tags
File 21 Io 13 Http 11 Json 8 Cli 8 Regex 8 Hash 7 Sort 7 Recursion 7 Serialization 7 Args 7 Concurrency Tag 6 Digest 6 Capture 6 Get 6 Web 6 Sha256 5 Async 5 Arrays 5 Sql 5 Loops 4 Functional 4 Threads 4 System 4 Encoding 3 Node 3 Errors 2 Server 2 Hashes 2 Find 2 Smtp 2 Walk 2 Glob 2 Routes 2 Curl 2 Email 2 Performance 2 Strings Tag 2 Url 2 Database Tag 2 Mysql 2 Password 1 Waitgroup 1 Promises 1 Portable 1 Requests 1 Optionparser 1 Websocket 1 Orm 1 Pdo 1
Languages
  • Bash 14
  • Go 14
  • JavaScript 14
  • Perl 14
  • PHP 14
  • Python 14
  • Ruby 14
  • Rust 14
© 2026 Code Snippets