CodeIgniter Forums
How to Check if database connection exists Ci4 - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: How to Check if database connection exists Ci4 (/showthread.php?tid=79643)



How to Check if database connection exists Ci4 - venance - 07-14-2021

I'm trying to check id database connection exist or not then redirect to a page where a user can be able to create a database through form inputs.

Here's what I tried to do but not succeed.

PHP Code:
public function index()
 {
 
// $database = \Config\Database::connect();
 
$database = \CodeIgniter\Database\Config::getConnections();

 if (
$database
 {
 
//db connection initialized
 
return view('dashboard');
 }
 else
 {
 
//db connection  not initialized
 
return redirect('db_setup');
 }
 } 



RE: How to Check if database connection exists Ci4 - InsiteFX - 07-14-2021

These are not tested but one of them should work for you.

PHP Code:
$db = \Config\Database::connect();


/* If an established connection is available, then there's
 * no need to connect and select the database.
 *
 * Depending on the database driver, conn_id can be either
 * boolean TRUE, a resource or an object.
*/
if ($db->initialize()){
    // we have a connection
} else {
    // NO Connections
}

// or try
if ($db->connID){


This is because CodeIgnioters database connection does not connect until a query is ran