Welcome Guest, Not a member yet? Register   Sign In
Creating a new database.
#1

(This post was last modified: 10-10-2022, 06:50 PM by davecoventry.)

I've been trying to follow the process for creating a new database, as detailed here: https://codeigniter4.github.io/userguide...se-db-name
PHP Code:
<?php
namespace App\Models;
use 
CodeIgniter\Model;
use 
CodeIgniter\Database\RawSql;

class 
InitiateDatabaseModel extends Model{
public function 
createDrawingTable($id){
    $dbName 'D'.$id;
    $forge = \Config\Database::forge();
    $forge->createDatabase($dbName,TRUE);

    $fields = array(
        'element'=>array(
                'type'=>'INT',
                'unsigned'=>true
            
),
        'eID'=>array(
                'type'=>'INT',
                'unsigned'=>true
            
),
        'txt'=>array(
                'type'=>'VARCHAR',
                'constraint'=>255
            
)
        );
$forge->addField($fields);
$forge->createTable('text'TRUE); 
The Database is not created but the table, with its fields, is added to the default database.
What am I doing wrong?
~ Dave
Reply
#2

You can also pass another database group name to the DB Forge loader, in case the database you want to manage isn’t the default one:

PHP Code:
$this->myforge = \Config\Database::forge('other_db'); 


You need to create a new database config for the database you want to use or it will default to the original one.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

Thanks!
Your response got me thinking and it occurred to me that my database user did not have permissions to create the new database.
Once I corrected this, the Model worked as expected...
Many thanks!
~ Dave
Reply
#4

Your welcome.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#5

Just to add that creating tables for the new database is not really straightforward and the code above generates an error when fields and tables are added: "InvalidArgumentException D8 is not a valid database connection group."

It seems that the new database needs an entry in \Config\Databases.php to establish a connection.

If I simply put "$this->db->simpleQuery('USE '.$dbName);", then the tables are added without error.

Hope this helps anyone seeking to do the same...
~ Dave
Reply




Theme © iAndrew 2016 - Forum software by © MyBB