Are there alternative methods to verify the existence of a database in PHP other than using mysql_select_db?
The mysql_select_db function is deprecated in PHP and should not be used for verifying the existence of a database. Instead, you can use the mysqli or PDO extension to connect to the database and then query the information_schema database to check if the desired database exists.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if the database exists
$query = "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = 'database_name'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
echo "Database exists!";
} else {
echo "Database does not exist.";
}
$conn->close();
?>
Related Questions
- What are some best practices for securely handling and processing external data in PHP scripts?
- How can one troubleshoot and resolve common errors like "unexpected T_STRING" when working with PHP control structures?
- Are there any best practices for handling multiple domains pointing to the same directory in PHP?