zizhost
PHP

Connecting PHP to MySQL

PDO connection example with credentials and basic queries.


Use PDO (recommended)

<?php
$dsn   = 'mysql:host=localhost;dbname=yourname_app;charset=utf8mb4';
$user  = 'yourname_dbuser';
$pass  = 'replace-me';

try {
    $db = 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);
    error_log($e->getMessage());
    exit('Database unavailable.');
}

A parameterised query

$stmt = $db->prepare("SELECT id, title FROM posts WHERE author_id = ? ORDER BY created_at DESC LIMIT 10");
$stmt->execute([$userId]);
foreach ($stmt as $row) {
    echo htmlspecialchars($row['title']);
}

Store credentials outside the document root

Keep db_config.php in your home directory (above public_html) and require it from your scripts. That way an Apache misconfiguration that ever served the directory raw still cannot leak your password.

Never concatenate user input into SQL

Always use prepared statements with placeholders. They are safe and faster, because MySQL caches the plan.