I'm trying to validating my insert data in codeigniter
The problem is the code returning me a duplicate entry's page error. And i want to throw that failure to home page with error message.
Here is my code:
$data = array(
'heheId' => $this->input->post('heheId'),
'userId' => $this->input->post('userId')
);
$this->db->insert('tentarasaya',$data);
if ($this->db->affected_rows() > 0){
$this->session->set_flashdata('info', "Hore sukses");
} else {
$this->session->set_flashdata('danger', "Fail insert");
}
redirect('my_home');
Any answer?
Update:
Duplicate entry like this
Try this
$data = array(
'heheId' => $this->input->post('heheId'),
'userId' => $this->input->post('userId')
);
if (!$this->db->insert('tentarasaya',$data)) { # add if here
# Unsuccessful
$this->session->set_flashdata('danger', "Fail insert");
}
else{
# Success
$this->session->set_flashdata('info', "Hore sukses");
}
redirect('my_home');
make sure that auto increment option is selected in your database. I am assuming that user_id here is a primary key, no need to insert that into a database yourself.
data = array(
'heheId' => $this->input->post('heheId'),
);
$this->db->insert('tentarasaya',$data);
Otherwise if you wish to insert user_ids yourself you can 1) define a custom call back function to check to see if the specified user id already exists in the database, 2) use the is_unique form validation rule that comes bundled with codeigniter
Related
Currently, I have controller & model for form edit. If user submit different value, this will modify the value in database and if there is an affected rows, will set flash message as "success" and if same data is submitted by user without modify the value,then will set flash message as "nochange".
if($this->db->affected_rows() > 0 ) {
$this->session->set_flashdata('success','Database is updated');
redirect('registrar');
} else {
$this->session->set_flashdata('nochange','There is no changes in database');
redirect('registrar');
}
In Codeigniter, how can I check if only specific columns are affected?
For example, if my table in database have 12 columns, if user only change the value let say in column 10, then set flash message as "nochange".
If user changes values in other columns except column 10, set flash message as "success"
There is no in-built functionality in CodeIgniter or php to do this.
You would have to essentially get the entire entry before updating it. And then column by column compare the submitted value with the current value of the entry as per your required logic.
Example pseudo-code:
$q = $this->db->get_where('table', array('id' => $id))->row();
$change = false;
if ($this->input->post('col1') !== $q->col1) {
$change = true;
}
...
if ($this->input->post('col10') == $q->col10) {
$change = false;
}
$this->db->update('table', $data);
This is one of my first applications out of tutorials so I don't know how to express my issue well.
Well I have these 2 tables:
User ( id, code )
Hours ( id, user_id, created)
I want to know how I can add an entry to the Hours table using the user_code.
I tried to grab the data of the User table with the code value and then findBy and pass for the patchEntity but it did not work.
I don't have a whole lot of information to work with, but I'll give it a go.
I want to know how I can add an entry to the Hours table using the
user_code
You mention using patchEntity, so that's updating information that's already there. Assuming user_code is the 'code' column you're talking about there, first find the user by his code:
$users_tbl = TableRegistry::get('Users');
// find the user
$user = $users_tbl->findByCode($user_code)->first();
if ($user) {
// replace '$this->request->data() with whatever patch data you wanted
$users_tbl->patchEntity($user, $this->request->data(), [
'associated' => ['Hours']
]
if ($users_tbl->save($user)) {
// success!
} else {
// error!
}
} else {
// error!
}
It will also depend on how you have the data you passed in (where my '$this->request->data() is, or whatever your array might be) - it needs to match the right column names and be in the correct format listed here.
However, this is updating the data. Just adding the data, you can load the hours table and add a new entry with the user_id acquired from the user search:
$hours_tbl = TableRegistry::get('Hours');
$hours = $hours_tbl->newEntity([
'user_id' => $user->id // $user populated from same method earlier
]);
/* assumed 'id' was autoincrementing and 'created' was populated
through Timestamp behavior */
if ($hours_tbl->save($hours)) {
// yay!
} else {
// boo
}
Problem: When editing an entry SQL is making an INSERT instead of an UPDATE.
I have two SQL tables : users and users_detail.
users(id,role,name,password) &
users_detail(id,adress,city,user_id)
Foreign key users_detail.user_id is linked to users.id.
I have a form in my cakephp app to edit users_detail, if a user wants to edit his adress for example.
Here is my controller :
public function admin_edit_dashboard($id = null){
if (!$this->User->exists($id)) {
throw new NotFoundException('Invalid user details');
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->UserDetail->save($this->request->data, true, ['id', 'address', 'city'])) {
$this->Session->setFlash('The user has been saved');
return $this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
} else {
//$this->request->data = $this->User->read(null, $id);
$user = $this->User->UserDetail->find('first', array(
'conditions' => array(
'UserDetail.user_id' => $id
)
));
$this->request->data = $user;
}
$this->set(compact('user'));
}
And my form :
<?php echo $this->Form->create('UserDetail');?>
<?php echo $this->Form->input('address', array('class' => 'form-control')); ?>
<br />
<?php echo $this->Form->input('city', array('class' => 'form-control')); ?>
<br />
<?php echo $this->Form->button('Submit', array('class' => 'btn btn-primary')); ?>
<?php echo $this->Form->end(); ?>
But when I'm validate the form to edit details I have an error :
Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'
Because the SQL query isn't an UPDATE but an INSERT. I don't know why.
SQL Query: INSERT INTO cake.user_details
(adress_ex, city_ex) VALUES ('roses street',
'London')
Thank you!
EDIT : It works, thanks for your help! Good code added.
You appear to have several problems.
$this->request->address is in correct. Form data is passed as $this->request->data so you should be using $this->request->data['UserDetail']['address'] etc.
If you want to make sure you only save specific fields you can pass these as the third parameter of save() and then you don't need to use set() beforehand:-
$this->UserDetail->save($this->request->data, true, ['id', 'address', 'city']);
The SQL error implies that your primary key on the user_details table is not set to auto-increment (which it should). Which is why an INSERT fails.
You are also forgetting to pass the primary key for the record you're trying to update so Cake assumes you want to create a new record. Make sure you include this so that Cake knows to use UPDATE. For example include the following in your View form:-
echo $this->Form->hidden('id');
Your User model should have association to UserDetail like:
public $hasOne = array('UserDetail');
and your in UserDetail:
public $belongsTo = array('User');
Then you don't have to use loadModel, just do:
$this->User->UserDetail->find('first', array(...));
And you should edit user details from UserDetailsController action.
In your view add lines to know what you are editing:
echo $this->Form->input('id');
And then just do save with passed $this->request->data. That should do it. And like I said, check table id in database, it has to be autoincrement.
You can't update just your table by telling in controller
$this->UserDetail->save($this->request->data)
Instead you should try to do something like
//find that specific row in database and then update columns and save it
$this->UserDetail->set(array('address'=>$request->address,'city'=>$request->city));
$this->UserDetail->save();
Your model wants to save it like a new user_details under id = 0 which already exists because you didn't specify that you want to update it and which columns you want to update.
Hope it helps
I have project with 3 application's sharing one codeigniter installation. It was working excellent until I changed name of mysql table, and changed query to reflect new changes to the database. Now it looks like my insert query is cached, and trying to insert value into old table (which doesn't exist anymore). This is what I've tried so far:
CI:
$this->db->cache_delete_all()
mysql:
RESET QUERY CACHE;
In config/database.php:
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
When db_debug configuration is set to TRUE it gives 500 error, when FALSE, I was able to catch error and it turn's out it's trying to insert into old table that doesn't exist anymore. I don't get how is this possible, I've even searched my complete project and can't find old table name anywhere in my project, also CI cache folders are empty. Any help would be appreciated.
EDIT: My insert code:
if($this->db->insert('booking_calendar', $data))
{
$booking_id = $this->db->insert_id();
$this->load->helper('string');
$order_id = strtoupper(random_string('alnum', 6)) . $booking_id;
$data = array(
'id' => $order_id,
'booking_calendar_id' => $booking_id,
'status' => 'PAYMENT_PENDING'
);
if($this->db->insert('bookings', $data))
{
$this->notifications->add($MYSELF['id'], 'Court successfully booked.');
return $order_id;
}
$this->notifications->add($MYSELF['id'], 'Court booking failed.', 'warning');
return false;
}
else
{
log_message('ERROR', 'Insert booking_calendar failed. ' . print_r($this->db->_error_message(), true));
}
And this is the output in my log:
ERROR - 2013-09-23 20:05:13 --> Insert booking_calendar failed. Table 'tennis.courts_calendar' doesn't exist
Notifications is custom class which just insert one row in "notifications" table.
I found answer to my problem, I had ON BEFORE INSERT/UPDATE triggers on my table, and when I changed it's name it turns out that inserting on the same table with new name was still triggering old table name instead of new one. So I just updated triggers and now it's working. Hope this will save time for someone else, because it took me a while even if it's looking trivial from this point of view now.
I have a form to edit a job, a job has a status column which can be 1, 2 or 3
<?php echo $this->Form->input('status', array('label' => '', 'options' => $status)); ?>
When i submit the form i want to check if the value of status is equal to 3, if it is then i want to send an email. BUT i dont want to send the email if the value was 3 already.
Is there an easy way in cakephp to check the previous value to the new value etc?
Thanks.
No need to mess with sessions, or indeed set the value beforehand.
Basically when you edit the record, you get the current records status value from the table. If it's already 3, we do not want to send an email, so set a boolean.
Update the record as required.
If the status was not 3, and the new status is, send the email.
I haven't filled in the whole method; but you should get the idea:
$send_email = true;
$current_status = $this->Job->field('status');
if($current_status==3) {
$send_email = false;
}
// save the record
if($send_email==true && $this->data['Job']['status']==3) {
//send the email
}
Read the existing record from the database just before you save the new one. You'd then have something to compare the new data against.
Or, store the status in the session and compare the new data against it.
So when you read the record from the database, save the status in session:
$this->data = $this->Job->read(null, $id);
$this->Session->write('JobStatus.'.$this->data['Job']['id'], $this->data['Job']['status']);
When the Job is edited, you can check the new value against the old one:
if (!empty($this->data)) {
if ($this->data['Job']['status'] == 3 && $this->Session->read('JobStatus.'.$this->data['Job']['id']) != 3) {
/**
* Send email
*/
}
}
You can set a hidden field with the source value and check it's value against the submitted one.
<?php echo $this->Form->input('old_status', array('type' => 'hidden', 'default' => $old_status)); ?>