MySQLi select_db Function Explained with Examples
The mysqli_select_db()
function is used to select a database for use with subsequent MySQLi queries. It's the procedural equivalent of creating a new MySQLi object with the database name.
Basic Syntax
bool mysqli_select_db(mysqli $link, string $dbname)
$link
: A MySQLi connection object$dbname
: The name of the database to select- Returns:
TRUE
on success,FALSE
on failure
Example 1: Basic Database Selection
<?php
// Create connection
$mysqli = mysqli_connect("localhost", "username", "password");
// Check connection
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
// Select database
if (mysqli_select_db($mysqli, "my_database")) {
echo "Database selected successfully";
} else {
die("Error selecting database: " . mysqli_error($mysqli));
}
// Now you can perform queries on the selected database
$result = mysqli_query($mysqli, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
echo "User: " . $row['username'] . "<br>";
}
// Close connection
mysqli_close($mysqli);
?>
Example 2: Alternative Approach (Recommended)
Instead of using mysqli_select_db()
, it's better to specify the database in the connection string:
<?php
// Connect and select database in one step (recommended approach)
$mysqli = mysqli_connect("localhost", "username", "password", "my_database");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected and database selected successfully";
// Use the connection for queries
$result = mysqli_query($mysqli, "SHOW TABLES");
echo "<h3>Tables in database:</h3>";
while ($row = mysqli_fetch_array($result)) {
echo $row[0] . "<br>";
}
mysqli_close($mysqli);
?>
Example 3: Switching Between Databases
<?php
// Connect to MySQL server
$mysqli = mysqli_connect("localhost", "username", "password");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
// Select first database
if (mysqli_select_db($mysqli, "database1")) {
echo "Selected database1<br>";
// Query first database
$result = mysqli_query($mysqli, "SELECT COUNT(*) as count FROM users");
$row = mysqli_fetch_assoc($result);
echo "Users in database1: " . $row['count'] . "<br>";
} else {
echo "Error selecting database1: " . mysqli_error($mysqli) . "<br>";
}
// Switch to second database
if (mysqli_select_db($mysqli, "database2")) {
echo "Selected database2<br>";
// Query second database
$result = mysqli_query($mysqli, "SELECT COUNT(*) as count FROM products");
$row = mysqli_fetch_assoc($result);
echo "Products in database2: " . $row['count'] . "<br>";
} else {
echo "Error selecting database2: " . mysqli_error($mysqli) . "<br>";
}
mysqli_close($mysqli);
?>
Example 4: Error Handling and Validation
<?php
// Database selection with comprehensive error handling
$mysqli = mysqli_connect("localhost", "username", "password");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
// List of databases to try
$databases = ["main_db", "backup_db", "test_db"];
$selected = false;
foreach ($databases as $db) {
if (mysqli_select_db($mysqli, $db)) {
echo "Successfully selected database: $db<br>";
$selected = true;
break;
} else {
echo "Failed to select database: $db - " . mysqli_error($mysqli) . "<br>";
}
}
if (!$selected) {
die("Could not select any database");
}
// Check if required tables exist
$tables = ["users", "products", "orders"];
foreach ($tables as $table) {
$result = mysqli_query($mysqli, "SHOW TABLES LIKE '$table'");
if (mysqli_num_rows($result) == 0) {
die("Required table '$table' does not exist in the selected database");
}
echo "Table '$table' exists<br>";
}
echo "Database is ready for use!";
mysqli_close($mysqli);
?>
Example 5: Dynamic Database Selection
<?php
// Function to select database based on environment
function getDatabaseConnection() {
$environment = getenv('APP_ENV') ?: 'development';
$config = [
'development' => [
'host' => 'localhost',
'user' => 'dev_user',
'pass' => 'dev_password',
'db' => 'dev_database'
],
'production' => [
'host' => 'prod.server.com',
'user' => 'prod_user',
'pass' => 'prod_password',
'db' => 'prod_database'
],
'testing' => [
'host' => 'test.server.com',
'user' => 'test_user',
'pass' => 'test_password',
'db' => 'test_database'
]
];
if (!isset($config[$environment])) {
die("Unknown environment: $environment");
}
$cfg = $config[$environment];
// Connect to server
$mysqli = mysqli_connect($cfg['host'], $cfg['user'], $cfg['pass']);
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
// Select database
if (!mysqli_select_db($mysqli, $cfg['db'])) {
// Try to create database if it doesn't exist (for development)
if ($environment === 'development') {
if (mysqli_query($mysqli, "CREATE DATABASE IF NOT EXISTS " . $cfg['db'])) {
mysqli_select_db($mysqli, $cfg['db']);
echo "Created and selected database: " . $cfg['db'] . "<br>";
} else {
die("Failed to create database: " . mysqli_error($mysqli));
}
} else {
die("Database not found: " . $cfg['db']);
}
}
return $mysqli;
}
// Usage
$mysqli = getDatabaseConnection();
echo "Successfully connected to database<br>";
// Perform queries
$result = mysqli_query($mysqli, "SELECT DATABASE() as db");
$row = mysqli_fetch_assoc($result);
echo "Current database: " . $row['db'] . "<br>";
mysqli_close($mysqli);
?>
Example 6: Object-Oriented Approach
<?php
// Object-oriented equivalent using MySQLi object
class DatabaseSelector {
private $mysqli;
public function __construct($host, $user, $pass) {
$this->mysqli = new mysqli($host, $user, $pass);
if ($this->mysqli->connect_error) {
die("Connection failed: " . $this->mysqli->connect_error);
}
}
public function selectDatabase($dbName) {
if ($this->mysqli->select_db($dbName)) {
echo "Selected database: $dbName<br>";
return true;
} else {
echo "Failed to select database: " . $this->mysqli->error . "<br>";
return false;
}
}
public function getConnection() {
return $this->mysqli;
}
public function close() {
$this->mysqli->close();
}
}
// Usage
$dbSelector = new DatabaseSelector("localhost", "username", "password");
if ($dbSelector->selectDatabase("my_database")) {
$mysqli = $dbSelector->getConnection();
// Use the connection
$result = $mysqli->query("SHOW TABLES");
echo "<h3>Tables:</h3>";
while ($row = $result->fetch_array()) {
echo $row[0] . "<br>";
}
}
$dbSelector->close();
?>
Example 7: Practical Application with Form
<?php
// HTML form to select database
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['database'])) {
$selectedDB = $_POST['database'];
$mysqli = mysqli_connect("localhost", "username", "password");
if (mysqli_select_db($mysqli, $selectedDB)) {
echo "<div style='color: green;'>Selected database: $selectedDB</div>";
// Show tables
$result = mysqli_query($mysqli, "SHOW TABLES");
echo "<h3>Tables in $selectedDB:</h3>";
echo "<ul>";
while ($row = mysqli_fetch_array($result)) {
echo "<li>" . $row[0] . "</li>";
}
echo "</ul>";
} else {
echo "<div style='color: red;'>Error: " . mysqli_error($mysqli) . "</div>";
}
mysqli_close($mysqli);
}
// Get list of databases
$mysqli = mysqli_connect("localhost", "username", "password");
$result = mysqli_query($mysqli, "SHOW DATABASES");
$databases = [];
while ($row = mysqli_fetch_array($result)) {
$databases[] = $row[0];
}
mysqli_close($mysqli);
?>
<!DOCTYPE html>
<html>
<head>
<title>Database Selector</title>
</head>
<body>
<h2>Select a Database</h2>
<form method="POST">
<select name="database" required>
<option value="">-- Select Database --</option>
<?php foreach ($databases as $db): ?>
<option value="<?php echo htmlspecialchars($db); ?>">
<?php echo htmlspecialchars($db); ?>
</option>
<?php endforeach; ?>
</select>
<button type="submit">Select Database</button>
</form>
</body>
</html>
Key Points to Remember
- Always check connection before selecting a database
- Use error handling to catch database selection failures
- Consider specifying database in connection instead of using
mysqli_select_db()
- The function returns boolean (
TRUE
on success,FALSE
on failure) - Database names are case-sensitive on some operating systems
Best Practices
- Specify database in connection string when possible
- Use consistent error handling throughout your application
- Validate database existence before attempting to select it
- Use appropriate privileges - the user must have access to the database
- Close connections when they're no longer needed
The mysqli_select_db()
function is useful when you need to switch between databases on the same connection, but for most use cases, it's better to specify the database directly in the connection parameters.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.