Cii Learner
Cii Learner

Reputation: 161

Mysql Update considering previous values

Here is my Table

SNo | UserId
1    | 1,2,3,

If i give the value 1 it should not change the values as it have already 1 and if i give 4 it should update as 1,2,3,4, and if i give the value 3,5 it should update as 1,2,3,5

The old values should not be deleted and it should only have the new values after the last comma

For the instance if i enter the value 1,4

I tried the query

UPDATE MyTable SET UserID='1,4' WHERE SNo = '1'

But it will replace

and the Table will be

SNo | UserId
1    | 1,4,

If i take the old value at the beginning of the query and concat it with the input then

Then value will be 1,2,3,1,4,

SNo | UserId
1    | 1,2,3,1,4,

How can i form the query for above all my conditions.

Upvotes: 1

Views: 64

Answers (2)

I'm Geeker
I'm Geeker

Reputation: 4637

Use this

UPDATE `users` SET `namedata` = CONCAT('1,2,3,4','5') WHERE FIND_IN_SET('3',namedata)

Upvotes: 1

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

Try this...

<?php
$os = array("1", "2", "3", "4");
$new="6";
$testdata=explode(",",$new);
for($i=0;$i<count($testdata);$i++)
{
if(in_array($testdata[$i],$os))
{

} else {
$os[]=$testdata[$i];
}
}
$final=implode(",",$os);

UPDATE MyTable SET UserID='$final' WHERE SNo = '1';
?>

Upvotes: 1

Related Questions