In codeigniter How i can check update? [duplicate] - php

This question already has answers here:
How can I detect a create, update, delete query is successful in Codeigniter
(2 answers)
Closed 2 years ago.
if($this->db->affected_rows()>0){
return TRUE;
}else{
return FALSE;
}
but in that case, if user dose not changed before information that in db's Info, it does not update.
So always return 0;
I want check update's Successful or fail
How I can Check?

Just use check like this
if($this->db->affected_rows()>=0){}

The best way is use transaction mechanism of codeigniter as below:
$this->db->trans_begin();//begins your transaction
$data =<data> //data for upadating
$this->db->where('id', $id);//where condition
$this->db->update('table_name',$data);//update query
if ($this->db->trans_status() === FALSE)//checks transaction status
{
$this->db->trans_rollback();//if update fails rollback and return false
return FALSE;
}
else
{
$this->db->trans_commit();//if success commit transaction and returns true
return TRUE;
}

Related

how to check if record inserted after a successful one in codeigniter [duplicate]

This question already has answers here:
How to test if Ci successfully inserted data
(4 answers)
Codeigniter Database Insert Failure
(2 answers)
Closed 3 years ago.
i get some information from user and want to add it into two related tables in my database. i add first one and check it with 'insert_id' then add second one.but problem is second 'insert_id' returns first tables inserted row id on failure. how can i check second insert query?
i'm using PHP 5, MySQL 5 and codeigniter 3
this is part of my controller:
$profile_result = $this->Profile_model->add($profile_data);
if ($profile_result)
{
$host_result = $this->Host_model->add([...]);
if (!$host_result)
echo 'error message';
}
Profile_model:
function add($options = array())
{
$this->db->insert("profile", $options);
return $this->db->insert_id();
}
and Host_model:
function add($options = array())
{
$this->db->insert("host", $options);
return $this->db->insert_id();
}
$host_result never gonna be false or 0.
but how can i check whether record added to host or not?

How transaction function in Codeigniter 3 works with the query?

So i have this query in my Models.
$this->db->trans_begin();
$this->db->insert($somequeryhere);
$this->db->insert($somequeryhere2);
$this->db->insert($somequeryhere3);
$this->db->insert($somequeryhere4);
$this->db->update($somequeryhere7);
$this->db->update($somequeryhere21);
$this->db->delete($somequeryhere10);
if($this->db->trans_status() === FALSE){
$this->db->trans_rollback(); return false;
}else{
$this->db->trans_commit(); return true;
}
The transaction sure works well. But it's confusing when i tried to die the PHP process in the middle of query like below query.
$this->db->trans_begin();
$this->db->insert($somequeryhere);
$this->db->insert($somequeryhere2);
$this->db->insert($somequeryhere3);
$this->db->insert($somequeryhere4);
die;
$this->db->update($somequeryhere7);
$this->db->update($somequeryhere21);
$this->db->delete($somequeryhere10);
if($this->db->trans_status() === FALSE){
$this->db->trans_rollback(); return false;
}else{
$this->db->trans_commit(); return true;
}
The transaction still works. I thought the PHP didn't reach $this->db->trans_status() so the transaction will not working, but this also works like using or without using $this->db->trans_status(). Could someone explain this ?
I have tried to used $this->db->trans_start(); and $this->db->trans_complete(); and the transaction rollback still executed.
If you Put a Die in middle of the code after trans_begin().
it will not commit, If you want to check the status of insert update data, you must not use the trans method for this one.
Because for trans method - commit or rollback need must to execute the query
//$this->db->trans_begin();
$this->db->insert($somequeryhere);
$this->db->insert($somequeryhere2);
$this->db->insert($somequeryhere3);
$this->db->insert($somequeryhere4);
die;
$this->db->update($somequeryhere7);
$this->db->update($somequeryhere21);
$this->db->delete($somequeryhere10);

CodeIgniter - Ensuring activerecord where statement has a criteria

Is the following code safe for deleting data?
public function remove($sc1_id = false)
{
if(!$sc1_id) redirect('backend/sections/index');
$sub_section_ids = $this->flatten($this->db->select('sc2_id')->from('sub_sections')->join('sections', 'sc2_sc1_id = sc1_id', 'INNER')->where('sc1_id', $sc1_id)->get()->result_array());
if($sub_section_ids)
{
$this->db->where_in('s2l_sc2_id', $sub_section_ids);
$this->db->delete('sub_section_prod_link');
}
$this->db->where('sc1_id', $sc1_id);
$this->db->delete('sections');
$this->db->where('sc2_sc1_id', $sc1_id);
$this->db->delete('sub_sections');
redirect('backend/be_sections/index');
}
I want to make sure that the where statements are being fullfilled. In testing, data has been wiped, so perhaps $sc1_id was truey, yet still not making a condition on the where statement, or perhaps I need to flush_cache() or reset_query() as well?
One thing I would add, it's a transaction statement. You're using more than one table for the delete process, if one of then fails you can't go back. So:
$this->db->trans_begin();
//your statements here
//if something goes wrong, just undo
if($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
//if everything is ok, proceed
else
{
$this->db->trans_commit();
redirect('to_somewhere');
}

How do I test if my MySQL update query was successful in CodeIgniter? [duplicate]

This question already has answers here:
How can I detect a create, update, delete query is successful in Codeigniter
(2 answers)
Closed 2 years ago.
I have a model function that updates a user in my CodeIgniter application:
// updates first of a user, return true if successful, false if not.
public function updateFirstName($userId, $newFirstName) {
$this->db->query("UPDATE users SET firstName='$newFirstName' WHERE id=$userId");
return // whether request was successful?
}
How do I return a boolean value that ensures the user of ID $userId has been updated? For instance, it should return false if no user was found with ID $userId.
As commented, have you tried $this->db->affected_rows()?
That will tell you how many rows were updated.
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return FALSE;
}
or
if ($this->db->affected_rows() > 0)
return TRUE;
else
return FALSE;
or
return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
EDIT
also(much better)
return ($this->db->affected_rows() > 0);
A better solution I've found is to manage the difference between an ERROR and 0 affected rows. 0 affected rows is not necessarily a bad thing, but an error is something you do want to know about:
if ($this->db->_error_message()) {
return FALSE; // Or do whatever you gotta do here to raise an error
} else {
return $this->db->affected_rows();
}
Now your function can differentiate...
if ($result === FALSE) {
$this->errors[] = 'ERROR: Did not update, some error occurred.';
} else if ($result == 0) {
$this->oks[] = 'No error, but no rows were updated.';
} else {
$this->oks[] = 'Updated the rows.';
}
Just some quick hacking there - you should obviously make the code far more verbose if you have other people using it.
The point is, consider using _error_message to differentiate between 0 updated rows and a real problem.
Check this for more information. Active Records
public function updateFirstName($userId, $newFirstName) {
return $this->db
->where('id', $userId)
->update("users", array('firstName' => $newFirstName));
}
With this way you will also avoid sql injection that you had before
You can use $this->db->affected_rows() in Codeigniter this returns a numeric value when doing "write" type queries (insert, update, etc.).
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. (From CI user guide). For deleted row in Ci it returns 1.
You may use $this->db->affected_rows(); to check whether query runs successfully or not
I have use this code for checking update query.
$status = $this->db->query("UPDATE users SET firstName='$newFirstName' WHERE id=$userId");
if($status)
return true;
else
return false;
public function updateInfo($newinfo) {
$this->db->update("some_table", $newinfo);
return ($this->db->affected_rows() > 0);
}
This will either return true or false
Use a stored procedure, you can check the result.
Below is a stored procedure example :
CREATE DEFINER=`root`#`localhost` PROCEDURE `usp_UpdateInfo`(tableId int,tableName varchar(100) charset utf8,description varchar(400) charset utf8)
BEGIN
declare exit handler for sqlexception select 0 as `result`;
update table
set `name` = tableName,
description = description
where id = tableId;
select 1 as `result` ;
END
PHP example code :
$this->load->database();
$rs = $this->db->query('call usp_UpdateInfo(?,?,?)',array($tableId,$tableName,$description));
$this->db->close();
return $rs->result_array();
Try this:
public function updateFirstName($userId, $newFirstName) {
$this->db->where('id', $userId);
$this->db->set('firstName', $newFirstName);
$sql = $this->db->update('users');
if ($sql) { return TRUE; } // $sql - boolean true or false
}

How do I tell when a MySQL UPDATE was successful versus actually updated data?

How do I tell when a MySQL UPDATE was successful versus actually updated data?
Example:
TABLE
id city_name
1 Union
2 Marthasville
If I run the following:
$data = array('city_name', 'Marthasville');
//update record 2 from Marthasville to the same thing, Marthasville.
$this->db->where('id', 2);
$this->db->update('table', $data);
if($this->db->affected_rows() > 0)
{
//I need it to return TRUE when the MySQL was successful even if nothing was actually updated.
return TRUE;
}else{
return FALSE;
}
This will return TRUE every time the UPDATE statement is successful, but FALSE when no rows were actually updated.
I need it to return TRUE every time the UPDATE statement was successfully executed even if it doesn't actually change any records.
Have a look at mysql_affected_rows()
It should tell you if anything was actually updated as opposed to nothing was successfully updated resulting in a return of true.
php.net says:
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last
query failed.
You could use the following to achieve your desired results:
if($this->db->affected_rows() >= 0){ }
Then you would use mysql_query:
SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query()
returns TRUE on success or FALSE on error.
Simple like this:
$result = $this->db->update('table', $data);
if($result)
{
//without error even no row updated
} else {
}

Categories