What is the best practice for checking if a database or table already exists in PHP?
When working with databases in PHP, it is important to check if a database or table already exists before attempting to create it. One common approach is to query the database system catalog to see if the database or table name is present. In PHP, this can be achieved by using SQL queries to check the existence of the database or table.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check if database exists
$result = $conn->query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'");
if ($result->num_rows == 0) {
echo "Database does not exist.";
} else {
echo "Database exists.";
}
// Check if table exists
$tableName = "table_name";
$result = $conn->query("SHOW TABLES LIKE '$tableName'");
if ($result->num_rows == 0) {
echo "Table does not exist.";
} else {
echo "Table exists.";
}
$conn->close();
?>