PHP

PDO Schema Existence Checks

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Idempotent helpers to test whether a table, column, or index already exists — handy when writing your own migration runner without an ORM.
PHP
Raw
<?php
function tableExists(PDO $db, string $dbName, string $table): bool {
    $s = $db->prepare('SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME=? LIMIT 1');
    $s->execute([$dbName, $table]);
    return (bool)$s->fetchColumn();
}

function columnExists(PDO $db, string $dbName, string $table, string $col): bool {
    $s = $db->prepare('SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1');
    $s->execute([$dbName, $table, $col]);
    return (bool)$s->fetchColumn();
}

function indexExists(PDO $db, string $dbName, string $table, string $idx): bool {
    $s = $db->prepare('SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND INDEX_NAME=? LIMIT 1');
    $s->execute([$dbName, $table, $idx]);
    return (bool)$s->fetchColumn();
}

if (!columnExists($db, 'myapp', 'users', 'avatar')) {
    $db->exec("ALTER TABLE users ADD COLUMN avatar VARCHAR(255) NULL");
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.