avenirer / CodeIgniter-MY_Model

Base model (MY_Model) for the Codeigniter framework.
324 stars 203 forks source link

where NULL is causing problems #295

Open nuryagdym opened 4 years ago

nuryagdym commented 4 years ago

When I say, $this->where('user_id', $some_value) ->update($update_data); it is not problem until we $some_value is NULL. if $some_value is NULL normally if we don't use MY_Model it is not problem BUT on MY_Model when $some_value = NULL then query becomes:

update mytable set update_field=value I mean where user_id IS NULL is not added which updates all the rows in table

I faced this problem several times, in accidently updated all rows, because without using MY_Model I don't have to control if $some_value is null in PHP, QB will generate WHERE user_id IS NULL thus, nothing will be updated.

salain commented 4 years ago

Here you can write your where like this

where('user_id IS NULL', NULL, FALSE,FALSE,FALSE,TRUE)

Result for a select query: SELECT * FROMtableWHERE user_id IS NULL It will give you the same WHERE clause for an UPDATE query.

nuryagdym commented 4 years ago

I know it, you did not understood me. I don't the where() function of MY_Model behave same as the QB of Codeigniter. For example, $this->where('user_id', $some_value) ->update($update_data); here I expect $some_value not to be NULL usually, but for some reason, code error (in my case was my fault, but I was testing) or to other kind of error, it is value is set to NULL. If I have this query with $some_value = NULL $this->where('user_id', $some_value) ->update($update_data); for QB it adds where user_id IS NULL condition, which I know that user_id's in that table are not NULL, so running this query with QB is safe. But when using MY_Model, it discards this where rule, and as result whole table was updated (which I don't want to it).

salain commented 4 years ago

Then you should validate $some_value to make sure it is not NULL. Rather than to hope the framework/library will do it for you.

nuryagdym commented 4 years ago

as I said I just expecting MY_Model behave same as QB in this case. Libraries are for making our job easier. if library expecting me where('user_id IS NULL', NULL, FALSE,FALSE,FALSE,TRUE) to write NULL conditions and IF checking everywhere it is nonsense. It needs tiny change, that is it.

emrahoruc commented 2 years ago

@nuryagdym Extend the MY_Model and add your methods.

class Base_Model extends MY_Model {  

    public function __construct()
    {
        parent::__construct();
    }

    public function whereNull($key)   
    {
        $this->where($key . ' IS NULL', NULL, FALSE,FALSE,FALSE,TRUE);
        return $this;
    }

    public function whereNotNull($key)   
    {
        $this->where($key . ' IS NOT NULL', NULL, FALSE,FALSE,FALSE,TRUE);
        return $this;
    }
}

// $this->Products_model->whereNull('user_id')->get_all();