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);
Related
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');
}
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;
}
So i have been pulling my hair out over this for the past two days. I have identified the problem down to this so far:
I am inserting some simple data into the database using Active Record:
if($this->db->insert('table', $data)){
return true;
}
else{
return false;
}
The problem is that it was always returning true whether the data got inserted or not. How i figured this out was that after several failed attempts when the data finally got inserted, the AUTO_INCREMENT ID was at 17, meaning that the insert query was running but failing to insert, hence always returning true. I want to know a reliable method of knowing whether data got inserted or not. Tried:
$this->db->affected_rows() > 0;
as well. But same issue prevails. It returns true.
If you have auto incremental id in your table then check $this->db->insert_id()
if greater the zero or us number then we can say data inserted or
again fire a sql query with id we get and if record exist then data is inserted
but i think that is not necessary just check insert_id
You need to insert your data first and get the result after. You will need to do something like this:
$this->db->insert('my_table', $my_data);
$is_inserted = $this->db->affected_rows() > 0;
if($is_inserted) {
echo 'Yay! Its works!';
} else {
echo 'Something went wrong. No insert ):'
}
You must perform your insert query before get the result. So you will need to run your insert and then get the affected rows. Codeigniter provides the class $this->db that help us to do this very easily. You can even get the inserted id running $this->db->insert_id() instead $this->db->affected_rows() to get the brand new inserted id.
You may find these links useful:
Query Helper Functions -
https://ellislab.com/codeigniter/user-guide/database/helpers.html
Active Record Class
https://ellislab.com/codeigniter/user-guide/database/active_record.html
Good Luck!
i always do this for check data is inserted or not
$this->db->insert('table', $data);
$id = $this->db->insert_id();
if($id)
{
echo "data inserted";
}
else
{
echo "data not inserted";
}
you can also do this also worked for me
$query = $this->db->insert('table', $data);
if($query)
{
echo "data inserted";
}
else
{
echo "data not inserted";
}
This is what I do. It works for me.
$this->db->set($data)->insert($table_name);
if ($this->db->affected_rows()) {
return $this->db->insert_id(); // or return true; in your case
}
return false;
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?
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 {
}