Update only one record with Code Igniter - php

Firstly, I will show what I want to do.
I want check if user has more than one record:
WHERE 'from_user_id' == '$id'
When query return > 0, I want update only ONE record where 'from_user_id' == '$id',
I dont care about order, It can be last or first record, but I have to update only one record.
Here is part of my model:
public function get_bonuses() {
if ($this->db->where('from_user_id', $this->user_id())->from($this->reff_table)->count_all_results()>0 ) {
$this->db->where('from_user_id', $this->user_id());
$this->db->update($this->reff_table, array('used' => '1'));
return true;
} else
return false;
}
It works fine but I want update only one record :<
I hope anyone will help me.
Regards
----- EDIT
SOLVED - I'm so stupid but I needed to look from the other side to my code :)
Here is working code:
if ($this->db->where(array('from_user_id' =>$this->user_id(), 'used' => '0' ))->from($this->reff_table)->count_all_results()>0 ) { $this->db->where(array('from_user_id' =>$this->user_id(), 'used' => '0' ))->limit(1); $this->db->update($this->reff_table, array('used' => '1')); return true;

If you want to update any one record from result, simply limit the query where you check count to 1 & grab its unique id (primary key) and update that row.

Related

I want to update Value but supervisor id update not properly it's update only first value where get employee_id

here I get supervisor id
I want to update all supervisor IDs where employee_id and employee are equal. When i update this value it's just an update of the single value for WorkingHierarchys Table. I try too much but I can't resolve this.
here update only one value for employee
here updated code
foreach($supervisors as $key=>$supervisor){
$work_hiechye['supervisor_id']=$supervisor;
$work_hiechye['employee_id']=$employee;
WorkingHierarchy::where('employee_id',$employee)->update($work_hiechye);
}
You will need to update the employee_id where the superviser_id is equal with $superviser and it will be something like this. I don't know your whole context, but what are you trying to do is not gone work.
foreach($supervisors as $supervisor) {
WorkingHierarchy::where([ 'superviser_id' => $supervisor ])->update([ 'employee_id' => $employee ]);
}

I am trying to update but it is adding a new row

this is my code for updating:
PS: empid is a foreign key but i think that shouldnt be the reason and the code is in CakePHP
if($this->request->is('post'))
{
$this->request->data["Leave"]["empid"] = $this->request->data["id"];
$this->Leave->empid = $this->request->data["Leave"]["empid"];
$this->request->data["Leave"]["leave_start"] = $this->request->data["start_date"];
$this->request->data["Leave"]["leave_end"] = $this->request->data["end_date"];
$this->request->data["Leave"]["leave_taken"] = $this->request->data["leave_taken"];
if($this->Leave->save($this->request->data['Leave']))
{
return $this->redirect(array('action' => 'manage_leave'));
}
}
// This code is inserting a new row instead of updating and also not adding any value in the new row
May be your trying to update the foreign table data using simple save.
Update multiple records for foreign key
Model::updateAll(array $fields, mixed $conditions)
Example
$this->Ticket->updateAll(
array('Ticket.status' => "'closed'"),
array('Ticket.customer_id' => 453)
);
Simple save for the primary key
Make sure that your HTML has empid
echo $this->Form->input('Leave.empid', array('type' => 'hidden'));
Save Model
$this->Leave->empid = $this->request->data["Leave"]["empid"]; //2
$this->Leave->save($this->request->data);
In between, you can also try to set the model data and check the $this->Leave->validates() and $this->Leave->validationError if they are giving any validation errors.
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);
// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);
You can find more information about all Saving your data
Hope this helps you :)
And in case if $empid is primary key of corresponding table of Leave model (e.g leaves), Just replace:
$this->Leave->empid = $this->request->data["Leave"]["empid"];
By
$this->Leave->id = $this->request->data["Leave"]["empid"];

Affected Rows not working - Codeigniter

I have this delete function in my model. When you press the delete button, it will subtract the number of total notes from the total notes column in my database. For eg. if you had 200 notes, and you deleted one of them, it will be 199 notes AND the note will be deleted from the database.
My code:
public function entry_delete($pid) {
$uid=$this->session->userdata('uid');
$whereConditions = array('pid' => $pid, 'uid' => $uid);
$this->db->where($whereConditions);
$this->db->delete('dayone_entries');
if ($this->db->affected_rows() == 0) {
$sql_entry = "UPDATE users set total_entry = total_entry - 1 WHERE uid = $uid";
$this->db->query($sql_entry);
return true;
} else {
return false;
}
}
But this doesn't work. I don't know why but when I press the delete button from my view, it will delete it from the database AND subtract -1 from my total_entry table. However, if I comment out the
$this->db->delete('dayone_entries');
It will still subtract 1 from the total_entry.
How do I fix this? Thanks.
I don't know if you have fixed this yet, but I think what Ghost was saying is your
if ($this->db->affected_rows() == 0) {}
is doing the wrong check. If you only want it to trigger if the rows where successfully deleted you would want to check
if ($this->db->affected_rows() > 0) {}
This is saying if the affected rows is more than 0 then do this. In CodeIgniter is says that the affected_rows() method is for "doing 'write' type queries (insert, update, etc.)".
It then goes on to say "Note: In MySQL "DELETE FROM TABLE" returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file." So if your if ($this->db->affected_rows() == 0) {} is triggering in both situations then this hack could be disabled because your asking "if the affected rows equals zero do this" and it should't trigger if your delete was successful.

Yii relations using variables of the active model

I have two rows in one of my tables which look like:
id product_id target_product_id description type
1 206587 456 sdfgdfgdfg 0
2 456 206587 fgdgfhghfgfdsgfdghfghfsd 0
When viewing the model for the row with id 1 I wish to get the second row based on where the product_id and the target_product_id are inversed. So I made a relation of:
'linked_product_relation' => array(self::HAS_ONE, 'Accessory', '',
'on'=>'linked_product_relation.target_product_id = product_id
AND link_product_relation.product_id = target_product_id')
However, it seems to only ever return null. I have checked that link_product_relation links to the table, and I get no SQL error, just a null return. If I use the relation with only link_product_relation.product_id = product_id though I do actually get a response, but only the row I am currently looking at. I seem to be missing something.
How can I get my desired output?
Edit
When I add a function to replace the relation:
function getTwinned(){
$a=Accessory::model()->findByAttributes(array('target_product_id'=>$this->product_id, 'product_id'=>$this->target_product_id));
if($a===null)
return null;
else
return $a;
}
It works perfectly.
You did not specify a foreign key ('' in your code). Try something like this:
'linked' => array(self::BELONGS_TO, 'Accessory', array(
'target_product_id'=>'product_id',
'product_id' => 'target_product_id',
)),
For more information also read the manual on this topic here and here.

CakePHP database queries in for loop

My code is below. I have an array, and by using this array I fill the database table. If some id exists in table, I update its row, if id doesn't exist than I create row and write data to row.
I empty my table and then run this code:
$arrayOfIds=array('1234', '5678');
foreach ($arrayOfIds as $twitter_user_id) {
$this->ModelName->twitter_user_id = $twitter_user_id;
if ($this->ModelName->exists()) {
echo "$twitter_user_id exists<br>";
} else {
echo "$twitter_user_id not exists<br>";
$this->ModelName->create( array ('twitter_user_id' => $twitter_user_id));
}
$data = array(
'ModelName' => array(
'age' => 15,
'last_status' => 'online'
));
$this->ModelName->save($data);
}
Result is echoed to screen:
1234 not exists
5678 exists
When I check table, 2 rows (twitter_user_id =1234 and twitter_user_id =5678) was added to table.
When I re-run my code with two entries in table, I also get this response:
1234 not exists
5678 exists
Do I miss something?
i think that exists() function is working not like you are thinking it must be :)
i would change this line:
if ($this->ModelName->exists()) {
to something like this:
if ($this->ModelName->find()) {
and if its not working as needed, add some condition to find function.. about your twitter_user_id

Categories