简体   繁体   中英

Codeigniter 4 query IF ISNULL

I am migragint from Codeigniter 3 to Codeigniter 4 and the next query is problematic to me.

In Codeigniter 3, the query was:

$this->db->query("UPDATE myTable SET data = '$data', 
                                myData = IF ( ISNULL(myData), '$state', CONCAT('$state', '-', myData) ) 
                        WHERE id = '$id'");

I tried to change this with the next format:

$data = array(
            'myData' => "IF( ISNULL(myData), " . $state. ", CONCAT(" . $state. ", '-', myData')")
        );

However, the function updates the content of $myData like a string "IF( ISNULL(myData), ". stateOfExample. ", CONCAT(". stateOfExample. ", '-', myData')".

I have looked into the CI4 documentation but i have not find the way to develop this query. I find the way to do that with the where() CI function, but i think is not the best way to do that.

Thanks in advance

If you put SQL functions in data, codeigniter won't understand that those are functions. It just adds them as string.

Put IF , CONCAT , ISNULL in sql and use data array just for variables.

$this->db->query("UPDATE myTable SET data = ?, 
    myData = IF ( ISNULL(myData), ?, CONCAT(?, '-', myData) ) 
    WHERE id = ?", array($data, $state, $state, $id));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM