Inserting NOW() into Database with CodeIgniter's Active Record - php

I want to insert current time in database using mySQL function NOW() in Codeigniter's active record. The following query won't work:
$data = array(
'name' => $name ,
'email' => $email,
'time' => NOW()
);
$this->db->insert('mytable', $data);
This is because CodeIgniter’s ActiveRecord class automatically escapes the input.
The following works fine, by calling set() and passing peratmeter FALSE, so that it doesn't escape the NOW().
$data = array(
'name' => $name ,
'email' => $email,
);
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
However, my question is that is there any other way than this? For example, if i can use somehow use by adding everything in the data array only?
For example, something like:
$data = array(
'name' => $name ,
'email' => $email,
'time' => NOW(), FALSE
);

I typically use triggers to handle timestamps but I think this may work.
$data = array(
'name' => $name,
'email' => $email
);
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);

Unless I am greatly mistaken, the answer is, "No, there is no way."
The basic problem in situations like that is the fact that you are calling a MySQL function and you're not actually setting a value. CI escapes values so that you can do a clean insert but it does not test to see if those values happen to be calling functions like aes_encrypt, md5, or (in this case) now(). While in most situations this is wonderful, for those situations raw sql is the only recourse.
On a side, date('Y-m-d'); should work as a PHP version of NOW() for MySQL. (It won't work for all versions of SQL though).

aspirinemaga, just replace:
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
for it:
$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);

This is the easy way to handle timestamp insertion
$data = array('created_on' => date('Y-m-d H:i:s'));

you can load the date helper and use the codeigniter interal now() if you want to reference the users GMT time offset
it woulk look somewhat like this
$data = array(
'created_on' => date('Y-m-d H:i:s',now())
);
If you don't use the GTM master settings and let your users set their own offsets there is no advantage over using php's time() function.

$data = array(
'name' => $name ,
'email' => $email,
'time' =>date('Y-m-d H:i:s')
);
$this->db->insert('mytable', $data);

According to the source code of codeigniter, the function set is defined as:
public function set($key, $value = '', $escape = TRUE)
{
$key = $this->_object_to_array($key);
if ( ! is_array($key))
{
$key = array($key => $value);
}
foreach ($key as $k => $v)
{
if ($escape === FALSE)
{
$this->ar_set[$this->_protect_identifiers($k)] = $v;
}
else
{
$this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
}
}
return $this;
}
Apparently, if $key is an array, codeigniter will simply ignore the second parameter $value, but the third parameter $escape will still work throughout the iteration of $key, so in this situation, the following codes work (using the chain method):
$this->db->set(array(
'name' => $name ,
'email' => $email,
'time' => 'NOW()'), '', FALSE)->insert('mytable');
However, this will unescape all the data, so you can break your data into two parts:
$this->db->set(array(
'name' => $name ,
'email' => $email))->set(array('time' => 'NOW()'), '', FALSE)->insert('mytable');

putting NOW() in quotes won't work as Active Records will put escape the NOW() into a string and tries to push it into the db as a string of "NOW()"... you will need to use
$this->db->set('time', 'NOW()', FALSE);
to set it correctly.
you can always check your sql afterward with
$this->db->last_query();

Using the date helper worked for me
$this->load->helper('date');
You can find documentation for date_helper here.
$data = array(
'created' => now(),
'modified' => now()
);
$this->db->insert('TABLENAME', $data);

$this->db->query("update table_name set ts = now() where 1=1")
also works for current time stamp!

run query to get now() from mysql i.e select now() as nowinmysql;
then use codeigniter to get this and put in
$data['created_on'] = $row->noinmyssql;
$this->db->insert($data);

Related

Codeigniter model with multiple update conditions using manual where statement

I have this code in model that returns data
$this->db->select('title, content, date');
$where = "name='Joe' AND status='boss'";
$this->db->where($where);
$query = $this->db->get('mytable');
return $query->result();
I am using a manual where and i wanted to know whether the concept of manual where in updates and possibly in deletes is allowed.
This code updates a table based on a single where condition
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
Is doing this allowed in codeigniter
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$where = "id=$id, name='Joe' AND status='boss'";
$this->db->where($where);
$this->db->update('mytable', $data);
As per document in CodeIgniter Where, you have to mention here with OR or AND "id=$id, name='Joe'.
$where = "id=$id AND/OR name='Joe' AND status='boss'";
^^^^
Chose one
Or use array

How to insert a data in a table in CodeIgniter

I'm having some trouble updating records with the Codeigniter framework. I'm using the MVC pattern and active records.
public function save_yarn($data)
{
$this->db->select('sub_name');
$this->db->from('mst_subject');
$this->db->insert($data);
}
This function should works for you:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
https://ellislab.com/codeigniter/user-guide/database/active_record.html#update
If you're using models for your tables, you can do something easy like
$this->yarn_model->update($row_id_to_update, $data);
Otherwise, Angel's method will work too.

insert and update at the same time with codeigniter

I have another problem again on querying in CodeIgniter,
I'll try to insert and update a "comment" on my website, but it's not working yet.
Here's my code :
on the Models (news_model.php)
public function simpan_komentar() {
$data = array(
'noid' => $_POST['noid'],
'kategori' => $_POST['kategori'],
'nama' => $_POST['nama'],
'pekerjaan' => $_POST['pekerjaan'],
'detail' => $_POST['detail'],
'created_at' => date('Y-m-d h:i:s'),
);
$data1 = array(
'komentar' => 'komentar + 1',
);
$this->db->insert('komentar',$data);
$this->db->update('news',$data1);
}
The insert query is working, but the update query didn't work
Can you tell me where's my fault?
Thanks
Try this
$this->db->set('komentar', 'komentar+1', FALSE);
//add your where condition if any
$this->db->update('news');

Codeigniter Escaping Data

I am using the following code to allow me to add data to my db but it seems the $this->db->escape();is not working as I can add html tags and they will run in the view :(
Code:
$this->form_validation->set_rules('aPartyLocation','A Party Location', 'required|trim|prep_for_form|max_length[35]|xss_clean');
$this->form_validation->set_rules('aPartyPhone','A Party Phone', 'required|trim|numeric|max_length[35]|xss_clean');
if($this->form_validation->run() === TRUE)
{
$userData = array(
'location' => $this->input->post('aPartyLocation', TRUE),
'phone' => $this->input->post('aPartyPhone', TRUE));
$this->db->escape($userData);
$this->party_model->addAParty($userData);
Update:
Controller:
$userData = array(
'id' => $id,
'location' => html_escape($this->input->post('aPartyLocation', TRUE)),
'phone' => html_escape($this->input->post('aPartyPhone', TRUE))
);
Model:
function addAParty($userData = NULL)
{
$this->db->insert('aParty',$userData);
return TRUE;
}
I would recommend you use CodeIgniter's Active Record class. This automatically escapes data for you.
For example, an insert statement would look like:
$this->db->insert('yourTable',array(
'location' => $this->input->post('aPartyLocation',TRUE),
'phone' => $this->input->post('aPartyPhone')
));
The second argument, is an array where the keys correspond to the columns in your database.
Edit
I believe Active Record only sanitizes data for SQL injection attacks. Passing the second parameter to $this->input->post() as TRUE protects your from XSS attacks. However, neither of those escape HTML tags. For that, you can use the htmlspecialchars function.
$this->db->insert('yourTable',array(
'location' => htmlspecialchars($this->input->post('aPartyLocation',TRUE)),
'phone' => htmlspecialchars($this->input->post('aPartyPhone'))
));
$location = $this->input->post('aPartyLocation',TRUE);
$phone = $this->input->post('aPartyPhone');
$this->db->insert('yourTable',array(
'location' => htmlspecialchars($location),
'phone' => htmlspecialchars($phone)
));

something's wrong with my cakePHP save method

i have a method inside a model, to do a simple save (insert to database), first it finds any users which meet certain conditions, and then insert certain info to another table to each of those found users, here's the code:
function save_emails(){
App::import('Model', 'User');
App::import('Model', 'EmailSave');
$this->EmailSave = new EmailSave();
$this->User = new User();
$users = $this->User->find("all", array(
'conditions' => array(
'OR' => array(
array('User.user_type_id' => '4'),
array('User.user_type_id' => '1')
)
),
'fields' => array(
'username',
'email'
),
'recursive' => -1
));
foreach($users as $user){
//pr($user);
$to = $user['User']['email'];
$subject = $email_template['subject'];
$template = //calling a templating method;
$save_send['EmailSave']['created'] = date("Y-m-d H:i:s", time());
$save_send['EmailSave']['modified'] = date("Y-m-d H:i:s", time());
$save_send['EmailSave']['send_to'] = $to;
$save_send['EmailSave']['subject'] = $subject;
$save_send['EmailSave']['message'] = $template;
//pr($save_send);
$this->EmailSave->save($save_send);
//echo $to."<br />".$subject."<br />".$template."<br />".$cron_id."<br />";
}
}
this is pretty much straight forward, i mean i am not using any complicated methods, now when i run the find method towards user :
$users = $this->User->find("all", array(
'conditions' => array(
'OR' => array(
array('User.user_type_id' => '4'),
array('User.user_type_id' => '1')
)
),
'fields' => array(
'username',
'email'
),
'recursive' => -1
));
it returns 2 results, and when i try to print the result using cake's pr method, it would print the right results, but...if i apply the save method, it would only insert one of the result, how is that possible? i have traced the codes line by line and it went through just find, the problem is when i save them to the database, it fails to save all 2 results, please help.
http://book.cakephp.org/view/1031/Saving-Your-Data
Creating or updating is controlled by the model's id field. If $Model->id is set, the record with this primary key is updated. Otherwise a new record is created.
When calling save() in a loop, don't forget to call create().

Categories