Malakiof
Malakiof

Reputation: 108

Concat string in mutliple rows with php/mysql or codeigniter

I would like to concat the same value to a field on multiple rows with a constraint..

With php/mysql, i'll do something like that:

$newdata = '33';

$sql = 'UPDATE users set relation=concat(relation,$newdata) 
       WHERE user_id IN (22, 31, 54)';

When the relation field is empty, this query is ok, but if the field is not empty (f.e relation:'8,56,78') i would like to concat ',33' with the coma in addition.

Have you an idea of how to do this without using multiple queries? I'd like to know if there is a way to do this in codeigniter too.

Thank you !

Upvotes: 1

Views: 682

Answers (2)

Mark
Mark

Reputation: 3272

SQL has IF-Statements:

"UPDATE users set relation= 
    CASE WHEN relation = '' 
        THEN $newdata 
        ELSE concat(relation,$newdata) 
    END
 WHERE user_id IN (22, 31, 54);"

Upvotes: 0

Ram Sharma
Ram Sharma

Reputation: 8819

try this query, if field will not have data than it will work in that case as well

$newdata = '33';

UPDATE users set relation = IFNULL (CONCAT( relation , $newdata ), $newdata) WHERE user_id IN (22, 31, 54)

Upvotes: 1

Related Questions