<Free PHP Code Snippets/>

A curated library of PHP scripts and snippets — ready to use, no database required. Browse by category, copy, and ship.

130+ Snippets
36 Categories
16 Languages
Free Always
Browse Categories
Featured Snippet

MySQL Connection Example

MySQL PHP

A clean, reusable MySQL connection snippet using PDO for modern PHP applications.

PHP
<?php
$host = 'localhost';
$db   = 'my_database';
$user = 'root';
$pass = 'secret';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>