phpmysqldatabasecodeigniter

All data is become NULL when run Update Query MySQL


I have a problem with mysql query update and I think it's so weird. I run Update query in my code with Where clause in that query. But, when I stop that query all the data in my table become NULL and this is not just in data contain in Where clause but in all the table.

This is my code :

$book = json_decode($this->input->post('stringify'));

foreach ($book as $row)
{
    $data = array(
              'price' => $row->price,
              'date_modified' => date("Y-m-d H:i:s"),
              'modified_by' => $row->username
           );

    $this->db->where('id', $row->id);
    $this->db->where('book_id', $row->book_id);
    $this->db->update('book_availability', $data);
}

I create that query with codeigniter framework. I just want to know why that query update all the data in my table and not just the data in Where clause. Maybe server cause that problem or anything possible to cause that. I hope someone could suggest me why it happen. Thanks.


Solution

  • It can happen if there is no value associated to variables which you are using for where condition

    It is always good to validate your data before inserting into database:

    foreach ($book as $row)
    {
      if(isset($row->id) && $row->id != '' && isset($row->book_id) && $row->book_id != '' ) {
        $data = array(
                  'price' => $row->price,
                  'date_modified' => date("Y-m-d H:i:s"),
                  'modified_by' => $row->username
               );
    
        $this->db->where('id', $row->id);
        $this->db->where('book_id', $row->book_id);
        $this->db->update('book_availability', $data);
       }
    }
    

    Now DB data will be updated only if you have values for given variables. You can use more validation like checking id if it is numeric (as per your DB structure ) or invalid.