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.
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');
}
}
Using the code from Virender Kumar but extending it with your request for dbname verification, use something like this:
$database = \Config\Database::connect();
if ($database)
{
// check if db exists:
if($database->query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='yourDbName'")) {
//db connection initialized
return view('dashboard');
} else {
return false; // db not exist
}
} else {
//db connection not initialized
return redirect()->to('db_setup');
}
Explanation: I added a CodeIgniter 4 raw query $db->query()
that selects the general information schema from the database. If the database does not exists you'll get an error.