The mysqli_select_db()
function in PHP is used to select a specific database to work with after a connection to the MySQL server has been established using mysqli_connect()
.
🔹 Syntax
mysqli_select_db(connection, database);
- connection: A
mysqli
object returned bymysqli_connect()
. - database: Name of the database to select.
✅ Example 1: Basic Usage
<?php
// Connect to MySQL server
$conn = mysqli_connect("localhost", "root", "", "");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Select database
if (mysqli_select_db($conn, "my_database")) {
echo "Database selected successfully.";
} else {
echo "Error selecting database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
✅ Example 2: Select Database After Connecting Without One
You can connect without specifying the DB name initially, and then select it using mysqli_select_db()
.
$conn = mysqli_connect("localhost", "username", "password");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Select the database later
mysqli_select_db($conn, "my_database");
🧠Note
- If the database is not found,
mysqli_select_db()
returnsfalse
. - This function is typically used when you want to switch databases after the connection or when the database name is not known at the time of connection.
✅ Alternative (in constructor)
You can also specify the database while connecting:
$conn = mysqli_connect("localhost", "username", "password", "my_database");
In this case, using mysqli_select_db()
is not necessary unless you want to change the database afterward.
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.