pull-icon
logo-mobile

PDO Prepared Statements

Home/Forums/PDO Prepared Statements

Bronze Member
Bronze Member

EmmaS

last month

Create PDO Prepared Statements

<?php
declare(strict_types=1);

// --- Database connection settings ---
$dsn  = 'mysql:host=localhost;dbname=db_name;charset=utf8mb4';
$user = 'db_user';
$pass = 'db_password';

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    exit("Database connection failed.");
}


// --- Prepared insert statement ---
$insert = $pdo->prepare("
    INSERT INTO people (username, gender, country)
    VALUES (:username, :gender, :country)
");


// --- Cleaner insert helper function ---
function addPerson(PDOStatement $stmt, string $username, string $gender, string $country): void {
    $stmt->execute([
        ':username' => $username,
        ':gender'   => $gender,
        ':country'  => $country,
    ]);
}


// --- Insert sample people ---
addPerson($insert, "Sarah",    "f", "Canada");
addPerson($insert, "Steve", "m", "India");

echo "People successfully inserted.";

?>

Leave a Comment

You must be logged in to post a reply.

Thank you ??

Thanks for supporting this station!

We've sent a download link to your email {}
Please check your inbox (and spam folder just in case).
The link will be valid for 24 hours.



BellOnline offers fast, reliable UK hosting with strong security and excellent uptime - perfect for modern radio and web projects.
MixStream provides broadcast-grade streaming with crystal-clear audio and rock-solid stability, ideal for both hobby and professional stations.

Goto BellOnline Now!

Close