PHP Redis: Get Current Database (Detailed Guide w/ Code Examples)
Use Case(s)
In PHP, using Redis, developers often need to retrieve the current database number they are connected with. This is particularly useful when working with multiple databases in Redis and to ensure that the correct operations are being performed on the intended database.
Code Examples
Here's an example of how to get the current database number using the SELECT
command:
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// Select a database.
$redis->select(2);
// Get the current database.
$currentDb = $redis->getDbNum();
echo "Current DB: " . $currentDb; // Outputs: Current DB: 2
?>
In this example, the select()
method is used to switch to the desired database and the getDbNum()
method is used to retrieve the currently selected database number.
Best Practices
- Always check the current database before performing operations when dealing with multiple databases. It helps avoid unexpected data manipulation.
- Handle exceptions or errors that may occur during the connection process or while switching databases.
Common Mistakes
Not checking the current database before conducting operations might lead to unintended modifications on the wrong database.
FAQs
Q: What if I try to select a database that doesn't exist? A: Redis will create it for you. Redis configuration defaults to 16 databases (numbered from 0 to 15), but you can increase this in your redis.conf file.
Was this content helpful?
Help us improve by giving us your feedback.
Similar Code Examples
- PHP Redis: Get All Keys Matching Pattern
- PHP Redis: Get All Keys Starting With
- PHP Redis - Get Hash Values at a Key
- Getting Memory Stats in PHP Redis
- Checking if a Key Exists in Redis using PHP
- Getting Number of Subscribers in Redis with PHP
- Getting a String Key using PHP and Redis
- Retrieving Multiple Keys in PHP Using Redis
- PHP Redis: Get Master Status
- Getting Default TTL with PHP Redis
- Getting Current Version of Redis in PHP
- Getting All Keys using PHP Redis
Free System Design on AWS E-Book
Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost