How can PDO be used to handle database selection dynamically in PHP scripts?
When needing to dynamically select a database in PHP scripts using PDO, you can achieve this by creating a PDO connection with the database information and then switching the database by executing a SQL query to change the database context. This can be useful when working with multiple databases or when the database needs to be selected based on certain conditions.
<?php
// Database connection information
$host = 'localhost';
$username = 'username';
$password = 'password';
// Create a PDO connection
$pdo = new PDO("mysql:host=$host;dbname=database1", $username, $password);
// Switch to a different database dynamically
$databaseName = 'database2';
$pdo->exec("USE $databaseName");
// Now you can perform queries on the selected database
$stmt = $pdo->query("SELECT * FROM table_name");
while ($row = $stmt->fetch()) {
// Process the data
}
?>
Related Questions
- Is it possible to have multiple optional parameters in a PHP function and only pass values to some of them?
- What steps should be taken to ensure that the 'ext' directory is properly located and utilized in a PHP5 package installation on Windows?
- What are the best practices for implementing authorization codes in PHP forms to restrict input based on specific time intervals?