What are best practices for connecting to the correct database and ensuring table and column existence in PHP scripts?

When connecting to a database in PHP scripts, it is important to ensure that you are connecting to the correct database and that the necessary tables and columns exist. One way to achieve this is by using error handling to catch any connection errors and querying the database to check for the existence of tables and columns before performing any operations.

<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Check if table exists
$table_name = "users";
$result = $conn->query("SHOW TABLES LIKE '$table_name'");

if($result->num_rows == 0) {
    die("Table $table_name does not exist");
}

// Check if column exists
$column_name = "email";
$result = $conn->query("SHOW COLUMNS FROM $table_name LIKE '$column_name'");

if($result->num_rows == 0) {
    die("Column $column_name does not exist in table $table_name");
}

// Perform database operations
// ...

$conn->close();
?>