PHP MySQL Heredoc to Test on Command Line

January 8, 2026 note-to-self k8s

I recently needed to test a MySQL connection in a k8s pod without an editor installed and running as a non-privileged user without installation rights on a read-only filesystem. This snippet helped make sure I once I was tunnelled to the host, it was working, isolating the issue to the tunnel.

php << 'EOF'
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$host = getenv('DB_HOST');
$user = getenv('DB_USERNAME');
$pass = getenv('DB_PASSWORD');
$db_name = getenv('DB_DATABASE');
$port = getenv('DB_PORT') ?: '3306';

if (empty($host) || empty($user) || empty($pass) || empty($db_name)) {
    echo "Error: Missing required env vars.\n";
    exit(1);
}

$dsn = "mysql:host=$host;port=$port;dbname=$db_name;charset=utf8mb4";
$query = "SELECT COUNT(*) FROM migrations";

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_TIMEOUT => 5
    ]);

    echo ":white_check_mark: Connected to {$host}:{$port}.\n";

    $stmt = $pdo->query($query);
    $result = $stmt->fetchColumn();

    echo "Total rows in 'migrations': " . $result . "\n";
    exit(0);

} catch (PDOException $e) {
    echo "DB Error: Failed to connect/query as {$user}. " . $e->getMessage() . "\n";
    exit(1);
}
EOF
Most posts are for my own reference and reflection, and shouldn’t be taken as fully accurate or instructional.