0

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?

1
  • 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. Commented Feb 5 at 22:09

1 Answer 1

0

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.";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.