I was working on a web application using CI4. I wanted to create a kind of install script if the database does not exist (implying the webapp is not installed).
The best I could get from CI4 was $forge->createDabase('db_name', True) to implement create database if not exists.
How can I check if the database exists so that if it exists, the work flows otherwise, the webapp is installed?
-
This question is similar to: How to check if mysql database exists. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.steven7mwesigwa– steven7mwesigwa2025-02-05 22:09:57 +00:00Commented Feb 5 at 22:09
Add a comment
|
1 Answer
CodeIgniter 4 does not provide a built-in method like databaseExists()
You can use the INFORMATION_SCHEMA.SCHEMATA table to check if the database exists before creating it like below function
function checkAndCreateDatabase($dbName)
{
// Load default database connection
$db = Config::connect();
$query = $db->query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?", [$dbName]);
// If database does not exist, create it
if ($query->getNumRows() == 0) {
$forge = \Config\Database::forge();
if ($forge->createDatabase($dbName)) {
echo "Database '{$dbName}' created successfully.";
} else {
echo "Failed to create database.";
}
} else {
echo "Database '{$dbName}' already exists.";
}
}