I'm learning CodeIgniter and now I wan to create MySQL table with DATETIME field.
I have this code in Install_Model.php
$Fields = array(
'ID' => array(
'Type' => 'INT',
'Constraint' => 10,
'Unsigned' => TRUE,
'Auto_Increment' => TRUE
),
'Username' => array(
'Type' => 'VARCHAR',
'Constraint' => '255'
),
'Password' => array(
'Type' => 'VARCHAR',
'Constraint' => '255'
),
'AddDate' => array(
'Type' => 'DATETIME'
)
);
$this->dbforge->add_key('ID', TRUE);
$this->dbforge->add_field($Fields);
$this->dbforge->create_table('Admins', TRUE);
echo 'Table Admins created successfully!<br/>';
When I execute this code I get this error:
Warning: #1265 Data truncated for column 'AddDate' at row 1
And in filed AddDate content is 0000-00-00 00:00:00
How I can fix problem, and make AddDate content current timestamp?
I tried to set DEFAULT CURRENT_TIMESTAMP but then CodeIgniter returns error in SQL query :(
Try
'AddDate' => array(
'type' => 'datetime',
'default' => '0000-00-00 00:00:00',
)
'AddDate' => array(
'type' => 'TIMESTAMP',
)
Add these in your model, it will automatically add current datetime on creation, updation adn deletion etc.
protected $createdField = 'AddDate';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
Related
I would like to have 2 timestamp/datetime fields, createdAt which only contains the time when the record was created but doesn't update constantly if there are updates on the record and updatedAt which generates during the time when the record was created and everytime the record gets updated. It's also said that a record should only contain one timestamp field at least for MySQL?
Here is my migration code:
$this->dbforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'name' => array(
'type' => 'VARCHAR',
'constraint' => '50',
),
'createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP'
));
How is this done using CodeIgniter DB Forge? Any answers are well appreciated. Thanks
Okay I got it, here is my solution:
$this->dbforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 5,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'name' => array(
'type' => 'VARCHAR',
'constraint' => '50',
),
'createdAt timestamp default now()',
'updatedAt timestamp default now() on update now()'
));
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.
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.
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',
In my Typo3 extension ,I want one of my table column as 'datetime' with type as'timestamp' and default as 'CURRENT_TIMESTAMP'.
How can I create this in TCA file.
I have given my code below. But this is not creating the column with type timespamp and default value as CURRENT_TIMESTAMP.
'datetime' => array(
'exclude' => 0,
'label' => 'LLL:EXT:besi_jobs/locallang_db.xml:tx_jobs_messages.datetime',
'config' => array(
'type' => 'timestamp',
'size' => '12',
'max' => '20',
'eval' => 'datetime',
'checkbox' => '0',
'default' => 'CURRENT_TIMESTAMP'
)
),
The type must be set to 'input':
'datetime' => array(
'exclude' => 0,
'label' => 'LLL:EXT:besi_jobs/locallang_db.xml:tx_jobs_messages.datetime',
'config' => array(
'type' => 'input',
'size' => '12',
'max' => '20',
'eval' => 'datetime',
'checkbox' => '0',
'default' => time(),
)
),
NOTES
All the possible types are described in the TCA reference.
The field in the .sql file file of your extension should be int(11) unsigned NOT NULL DEFAULT '0'. The TCA definition neither creates nor alters the database. It only defines how the field is displayed in the forms.