What are the best practices for handling database connections in PHP when checking for table existence?

When checking for table existence in PHP, it is important to handle database connections properly to avoid performance issues and potential security vulnerabilities. It is recommended to establish a database connection using PDO or MySQLi, check for table existence using SQL queries, and properly handle any exceptions that may occur during the process.

<?php

// Establish a database connection using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
    die('Database connection failed: ' . $e->getMessage());
}

// Check for table existence
$tableName = 'my_table';
$stmt = $pdo->query("SHOW TABLES LIKE '$tableName'");
$tableExists = $stmt->rowCount() > 0;

// Handle table existence
if ($tableExists) {
    echo 'Table exists!';
} else {
    echo 'Table does not exist.';
}

// Close the database connection
$pdo = null;

?>