CodeIgniter Migration - php

I've started to study CodeIgniter migrations do improve the development standards on my new job.
But, by some reason, I'm unable to create any table on my database.
Above the migration code:
<php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Create_users_table extends CI_Migration {
public function __construct()
{
parent::__construct();
$this->load->dbforge();
}
public function up()
{
$fields = array(
'user_id' => array(
'type' => 'INT',
'constraint' => 11,
'unique' => TRUE,
'null' => FALSE,
'auto_increment' => TRUE
),
'user_name' => array(
'type' => 'VARCHAR',
'constraint' => '255',
'null' => FALSE,
),
'user_email' => array(
'type' => 'VARCHAR',
'constraint' => '255',
'null' => FALSE,
),
'user_password' => array(
'type' => 'VARCHAR',
'constraint' => '255',
),
'user_status' => array(
'type' => 'INT',
'constraint' => 1,
'default' => 0
),
'user_permissions' => array(
'type' => 'VARCHAR',
'constraint' => '255',
),
'device_token' => array(
'type' => 'VARCHAR',
'constraint' => '255',
),
'user_level' => array(
'type' => 'INT',
'constraint' => 3,
'default' => '=9'
),
'user_photo' => array(
'type' => 'VARCHAR',
'constraint' => '255',
),
'device_snid' => array(
'type' => 'VARCHAR',
'constraint' => '255',
),
'user_recovery_token' => array(
'type' => 'VARCHAR',
'constraint' => '255',
),
'client' => array(
'type' => 'INT',
'constraint' => 11,
'null' => FALSE,
'default' => 0
),
'latitude' => array(
'type' => 'VARCHAR',
'constraint' => '255',
),
'longitude' => array(
'type' => 'VARCHAR',
'constraint' => '255',
)
);
$this->dbforge->add_field($fields);
$this->dbforge->add_key('user_id', TRUE);
$attributes = array('ENGINE' => 'InnoDB');
try{
$this->dbforge->create_table('users',TRUE,$attributes);
echo '<pre>Table created</pre>';
} catch(Exception $e ){
echo '<pre>Error creating table.</pre>';
d($e);
}
$this->db->query(" INSERT INTO `users` VALUES (1, 'SYSTEM', 'NOUSERNAME', '111', 0, NULL, NULL, NULL, -9, NULL, NULL, NULL, 1, NULL, NULL)");
}
public function down()
{
$this->dbforge->drop_table('users',TRUE);
}
}
Migration fileName: /aplication/migrations/20181129120800_Create_users_table.php
Controller method to run the migration:
public function do_migration($version = NULL)
{
$this->load->library('migration');
if(isset($version) && ($this->migration->version($version) === FALSE))
{
show_error($this->migration->error_string());
}
elseif(is_null($version) && $this->migration->latest() === FALSE)
{
show_error($this->migration->error_string());
}
else
{
echo 'The migration has concluded successfully.';
}
}
The CodeIgniter creates the 'migrations' table and set the "version" as the timestamp of the filename, as expected.
The 'users' table aren't beign created. The debug message "table created" is printed.
If I test the method $this->dbforge->create_table('users',TRUE,$attributes); it returns false.
Tryed to debug and try/catch for errors but the only result is bool(false).
If I create any table and select the data on them the CI returns it, as expected, because the DB connection is OK.
EDIT
Find the problem: inside the fields there was an typo on user_level where default was set to "=9" (invalid integer), when it was intended to be "-9".

The problem is trying to catch an exception because dbforge does not throw any exceptions. You should revert to the good old if conditional.
if($this->dbforge->create_table('users',TRUE,$attributes) === FALSE)
{
echo '<pre>Error creating table.</pre>';
return;
}
echo '<pre>Table created</pre>';
$res = $this->db->query(" INSERT INTO `users` VALUES (1, 'SYSTEM', 'NOUSERNAME', '111', 0, NULL, NULL, NULL, -9, NULL, NULL, NULL, 1, NULL, NULL)");
echo $res ? '<pre>Insert Succeeded</pre>' : '<pre>Insert Failed</pre>';
Not related to your problem, but you do not need a __construct method in Migration_Create_users_table. The dbforge library is loaded by the parent class CI_Migration. There is no reason to override CI_Migration::__construct and if you did have a reason, a to call parent::__construct($config); would be an absolute necessity. (Oh, and the extending class would have had needed to accept a $config parameter in its constructor.)
In case that last paragraph isn't clear (yes, I rambled on) remove the constructor from Migration_Create_users_table.

Related

Not able to call another controller method in codeigniter

I am creating a new database as part of the setup for each of my tenants, db is created successfully but is taking a lot of time , approx 5 min, on the other hand i am not able to call another controller method i.e admin_list controller and manage_package method inside it. This is my controller code:
<?php
class login extends CI_Controller
{
var $data;
function __construct() {
parent::__construct();
$this->load->helper('cookie');
require_once(APPPATH.'controllers/admin_list.php');
$is_admin_logged_in = $this->admin_init_elements->admin_logged_in_status();
global $USER;
if($is_admin_logged_in == TRUE){
redirect('home');
//;
}
//populate viewfor header / footer elements
$this->admin_init_elements->init_elements('N');
$this->load->model('mod_login');
}
public function save_userinput()
{
//code goes here
// for example: getting the post values of the form:
$form_data = $this->input->post();
// or just the username:
$username = $this->input->post("username");
echo $username;
// $this->admin_list->manage_package();
$this->load->dbforge();
if ($this->dbforge->create_database($username))
{
try{
$current_database = $username;
$this->db->database = $current_database;
$this->db->close();
$config['hostname'] = "localhost";
$config['username'] = "root";
$config['password'] = "";
$config['database'] = $current_database;
$config['dbdriver'] = "mysql";
$config['dbprefix'] = $username;
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$this->load->database($config);
$fields = array(
'id' => array(
'type' => 'INT',
'constraint' => 11,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'home_bg' => array(
'type' => 'VARCHAR',
'constraint' => '200',
),
'login_bg' => array(
'type' => 'VARCHAR',
'constraint' => '200',
),
'other_bg' => array(
'type' =>'VARCHAR',
'constraint' => '200',
),
'uploaded_on' => array(
'type' => 'DATE',
),
);
$this->dbforge->add_field($fields);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('pr_backgrounds', TRUE);
$fields = array(
'id' => array(
'type' => 'BIGINT',
'constraint' => 15,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'username' => array(
'type' => 'VARCHAR',
'constraint' => '255',
'default' => 'admin#fold.com',
),
'userpass' => array(
'type' => 'VARCHAR',
'constraint' => '255',
'default' => '65e1b655a6d6f4cbed20554d3b52521a743afdc0',
),
'email' => array(
'type' =>'VARCHAR',
'constraint' => '255',
'default' => 'admin#fold.com',
),
'departmentid' => array(
'type' => 'BIGINT',
'constraint' => 15,
'default' => '1',
),
'userroleid' => array(
'type' => 'BIGINT',
'constraint' => 15,
'default' => '4',
),
'managerid' => array(
'type' =>'VARCHAR',
'constraint' => '255',
'default' => '10',
),
'userlevel' => array(
'type' => 'INT',
'constraint' => 11,
),
'branchid' => array(
'type' => 'INT',
'constraint' => 11,
'default' => '2',
),
'is_global' => array(
'type' => 'TINYINT',
'constraint' => 4,
'default' => '0',
),
'registrationtime' => array(
'type' => 'INT',
'constraint' => 10,
),
'timemodified' => array(
'type' => 'BIGINT',
'constraint' => 10,
),
'modifierid' => array(
'type' => 'BIGINT',
'constraint' => 15,
),
'status' => array(
'type' => 'TINYINT',
'constraint' => 1,
),
'deleted' => array(
'type' => 'TINYINT',
'constraint' => 1,
),
'temppass' => array(
'type' => 'VARCHAR',
'constraint' => 20,
),
'temppassvalidtill' => array(
'type' => 'BIGINT',
'constraint' => 15,
),
'lastlogin' => array(
'type' => 'BIGINT',
'constraint' => 10,
),
'lastrefresh' => array(
'type' => 'BIGINT',
'constraint' => 15,
),
'lastloginip' => array(
'type' => 'VARCHAR',
'constraint' => 20,
),
'if_online' => array(
'type' => 'INT',
'constraint' => 11,
),
'pfield' => array(
'type' => 'VARCHAR',
'constraint' => 255,
),
);
$this->dbforge->add_field($fields);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('pr_users', TRUE);
$sql = file_get_contents("assets/bizzlatestdb.sql");
/*
Assuming you have an SQL file (or string) you want to run as part of the migration, which has a number of statements...
CI migration only allows you to run one statement at a time. If the SQL is generated, it's annoying to split it up and create separate statements.
This small script splits the statements allowing you to run them all in one go.
*/
$sqls = explode(';', $sql);
array_pop($sqls);
foreach($sqls as $statement){
$statment = $statement . ";";
$this->db->query($statement);
}
}
catch(Exception $e){
echo "This name already exists in our database , Please choose another company name";
die;
}
$this->admin_list->manage_package();
}
// then do whatever you want with it :)
}
function index(){
$this->load->view('login', $this->data);
}
}
?>
You can load controller as library in Codeigniter2. But I don't think it is possible in Codeigniter3.
Load Controller as Library :
$this->load->library('../controllers/controller_name');
# Calling Methdod
$this->controller_name->method_name();

How to set Datetime as type for a column on Codeigniter migration

I am doing a migration file, and there is a field on a table wich type should be DateTime, and the default value CURRENT_TIMESTAMP. What I have until now is the next:
'date' => array(
'type' => 'DATETIME',
),
I think it is right... but I still need set the default value... definitely, what I want to do is make the translation from sql to codeigniter migration of this:
`date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
Thanks in advance.
Best way to Codeigniter migration:
$this->dbforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'first_name' => array(
'type' => 'VARCHAR',
'constraint' => '50',
'null'=>false,
),
'last_name' => array(
'type' => 'VARCHAR',
'constraint' => 50,
'null'=>false,
),
'email' => array(
'type' => 'VARCHAR',
'constraint' => 100,
'unique' => true,
'null'=>false,
),
'mobile' => array(
'type' => 'BIGINT',
'constraint' => 15,
'null'=>true,
),
'password' => array(
'type' => 'VARCHAR',
'constraint' => 255,
'null'=>false,
),
'image' => array(
'type' => 'VARCHAR',
'constraint' => 255,
'null'=>true,
),
'status' => array(
'type' => 'TINYINT',
'constraint' => 3,
'default'=>1,
),
'delete_status' => array(
'type' => 'TINYINT',
'constraint' => 3,
'default'=>1,
),
'created_date datetime default current_timestamp',
'updated_date datetime default current_timestamp on update current_timestamp',
));
You can try like this.Need to use timestamp.See an example below..
'created_at' => array('type' => 'timestamp')
I have found this answer in the codeigniter forum. Basically, it says that I can use created_at timestamp default current_timestampinstead of key->value array. And there are other interesant things like 'on update':
'updated_at' => array(
'type' => 'varchar',
'constraint' => 250,
'null' => true,
'on update' => 'NOW()'
)
I hope it can to help anyone on future.

how to set on update attributes in a timestamp field using dbforge class in codeigniter 3

I want to set on update attributes for getting an updated time for my application. Here is my Model Code:
public function createDatabase() {
$testdatabase = "testdatabase";
$this->dbforge->create_database($testdatabase);
$this->db->db_select($testdatabase);
$fields = array(
'id' => array(
'type' => 'INT',
'constraint' => 1,
'unsigned' => TRUE,
),
'name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
'establishment_date' => array(
'type' => 'VARCHAR',
'constraint' => '50',
'null' => TRUE,
),
'package' => array(
'type' => 'VARCHAR',
'constraint' => '15',
),
'db_name' => array(
'type' => 'VARCHAR',
'constraint' => '25',
),
'update_date' => array(
'type' => 'datetime',
'on update' => 'NOW()',
),
'upgrade' => array(
'type' => 'tinyint',
'constraint' => '1',
'default' => '0',
),
'status' => array(
'type' => 'tinyint',
'constraint' => '1',
'default' => '4',
),
);
$this->dbforge->add_field($fields);
$this->dbforge->add_field("subscription_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
$this->dbforge->add_field("subscription_expire TIMESTAMP DEFAULT '0000-00-00 00:00:00'");
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('tms_profile');
}
Table is successfully created but on update attributes not exists on the field named update_date. i want to set on update atrributes on the field.
All you have to do is change type of update_date column like
....
'update_date' => array(
'type' => 'TIMESTAMP'
),
.....
Now it will work ON UPDATE with NOW()
use inline declaration, like here:
`update_stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',

How to run multiple migrate file in CodeIgniter at once?

I am creating a migrate and at first table it seems ok but when I created my second migration there's no error but the table is not created.
I named my 2 migration class like this:
001_inititial_schema.php
002_create_table_quotation_header.php
The first one contains this:
class Migration_Initial_Schema extends CI_Migration {
public function up() {
$this->dbforge->add_field(array(
'id' => array(
'type' => 'int',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true
),
'project_name' => array(
'type' => 'varchar',
'constraint' => 100,
),
'description' => array(
'type' => 'text'
),
'date_created' => array(
'type' => 'datetime',
),
'date_updated' => array(
'type' => 'datetime',
),
'status' => array(
'type' => 'tinyint',
'default' => 1
),
));
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('flx_project');
}
public function down() {
$this->dbforge->drop_table('flx_project');
}
}
Then the second one:
class CreateTableQuotationHeader extends CI_Migration {
public function up() {
$this->dbforge->add_field(array(
'id' => array(
'type' => 'int',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true
),
'project_id' => array(
'type' => 'int',
'constraint' => 11,
'unsigned' => true,
),
'receiver' => array(
'type' => 'varchar',
'constraint' => 100,
),
'address' => array(
'type' => 'text',
),
'attention' => array(
'type' => 'varchar',
'constraint' => 100
),
'reference_number' => array(
'type' => 'varchar',
'constraint' => 50
),
'date_issued' => array(
'type' => 'date'
)
));
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('flx_project_header');
}
public function down() {
$this->dbforge->drop_table('flx_project_header');
}
}
Then in my controller:
<?php
class Migrate extends CI_Controller {
public function __construct() {
parent::__construct(0);
$this->load->library('migration');
}
public function index() {
$this->load->helper('template');
if(!$this->migration->current()) {
show_error($this->migration->error_string());
} else {
$data['message'] = 'migrate success';
}
renderPage('common/migrate', $data);
}
}
?>
Ok I solved my problem what I did is I include both the migration in 1 file only. But I don't know if it is a proper way in runnning the migration that has a multiple tables.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Initial_Schema extends CI_Migration {
public function up() {
$this->dbforge->add_field(array(
'id' => array(
'type' => 'int',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true
),
'project_name' => array(
'type' => 'varchar',
'constraint' => 100,
),
'description' => array(
'type' => 'text'
),
'date_created' => array(
'type' => 'datetime',
),
'date_updated' => array(
'type' => 'datetime',
),
'status' => array(
'type' => 'tinyint',
'default' => 1
),
));
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('flx_project');
$this->dbforge->add_field(array(
'blog_id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'blog_title' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
'blog_description' => array(
'type' => 'TEXT',
'null' => TRUE,
),
));
$this->dbforge->add_key('blog_id', TRUE);
$this->dbforge->create_table('blog');
}
public function down() {
$this->dbforge->drop_table('flx_project');
$this->dbforge->drop_table('blog');
}
}
?>

drupal_write_record in drupal 6 returning false

When I run drupal_write_record, it always comes back false. I've debugged into the function and see that drupal_get_schema function, found inside drupal_write_record function, returns false. Further more, if I debug into drupal_get_schema function and look at
$schema = $cached->data;
My new table is not included in the $schema array. I've tried flushing the cache, reinstalling the module, and running update.php but nothing helps. In the event it helps, I've also included the .install file I wrote that adds the new table to the database:
<?php
// $Id: my_module.install,v 1.00.0.1 2012/10/21 00:23:32 Exp $
/**
* Implementation of hook_schema().
*/
function my_module_schema() {
$schema = array();
$schema['my_module_pending_inserts'] = array(
'fields' => array(
'id' => array(
'description' => 'primary key',
'type' => 'serial',
'size' => 'tiny',
'not null' => TRUE,
),
'json_array_data' => array(
'type' => 'text',
'not null' => TRUE,
),
'successfully_run' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
),
'date_created' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
),
'date_updated' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
)
),
'primary key' => array('id'),
);
return $schema;
}
function jira_reporting_install() {
// Create tables.
drupal_install_schema('my_module_pending_inserts');
}
function my_module_uninstall() {
// Remove tables.
drupal_uninstall_schema('my_module_pending_inserts');
// Delete variables
variable_del('my_module_variable1');
variable_del('my_module_variable2');
variable_del('my_module_variable3');
}
function my_module_update_2() {
$up = array();
$tbl = array(
'fields' => array(
'id' => array(
'type' => 'serial', 'not null' => TRUE
),
'json_array_data' => array(
'type' => 'varchar',
'length' => 250,
'not null' => True
),
'successfully_run' => array(
'type' => 'int'
),
'date_created' => array(
'type' => 'int'
),
'date_updated' => array(
'type' => 'int'
),
),
'primary key' => array('id'),
);
db_create_table(&$up, 'my_module_pending_inserts', $tbl);
return $up;
}
never mind, it was a typo in my _schema name

Categories