I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4.
I use migration files (001_create_authors.php
up to 005_create_comments.php
) to automatically create the necessary database tables.
The controller running the migrations is at
application/controllers/Migrate.php
It has the flowing code:
class Migrate extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->library('migration');
if($this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
else {
echo 'Migration executed';
}
}
}
The default controller is the Posts
controller, as the routes.php
file shows: $route['default_controller'] = 'posts';
I would like the Posts
controller to redirect to the Migrate
one, if there are no tables in the database. Does Codeigniter have a method to determine if there are no tables? How shall I use it?
https://www.codeigniter.com/user_guide/database/metadata.html
if (count($this->db->list_tables()) == 0) {
redirect(...);
}
I got the desired result this exact way:
In the Posts controller (default):
public function index() {
// Create all the database tables if there are none
// by redirecting to the Migrations controller
if (count($this->db->list_tables()) == 0) {
redirect('migrate');
}
// More code
}
In the Migrate controller:
class Migrate extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->library('migration');
if($this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
else {
$this->session->set_flashdata('tables_created', "All the required database tables have been created. You can now register.");
redirect('/');
}
}
}