Delete a specific ID inserted as serialize in a column in Mysql

Asked

Viewed 193 times

0

In my db I have a column called Range_ids, I do an ID insertion using the function serialize. These Ids look like an array, the problem is how I can make one DELETE of the specific ID within the column.

//Usando a função serialize eu insiro esses ids 1052,1053..... em serie

+------------+----------+--------------------------------------------+
| id         | nome     | Range_ids                                  |
+------------+----------+--------------------------------------------+
| 01         | Prod1    | a:2:{i:1052;s:4:"1052";i:1053;s:4:"1053";} |
| 02         | Prod2    | a:2:{i:1052;s:4:"1052";i:1053;s:4:"1053";} |
| 03         | Prod3    | a:2:{i:1052;s:4:"1052";i:1053;s:4:"1053";} |
+------------+----------+--------------------------------------------+

The problem is how I delete a specific ID on the specific line. Example: I want to remove the number 1052 from the column range_id on line 1

//Precisaria de Algo assim
<a href="del.php?id_range=1052">Deletar</a>

1 answer

0

Here’s what you’d have to do:

<?php
$num = "1052";
$sql = "SELECT range_ids FROM tabela";
if($query = $conn->query($sql)){
while($row = $query->fetch_assoc()){
    $linha[] = $row["range_ids"];
}
}
//var_dump($linha);
$db_range = $linha;
if(is_array($db_range)){
    foreach($db_range as $range){
        $un_dbrange = unserialize($range);
        //var_dump($un_dbrange);
        foreach($un_dbrange as $key=>$value){
            if($value == $num){
                unset($un_dbrange[$key]);
            }
        }
    }
}
echo "<hr/>";
var_dump($un_dbrange);
?>

See how not pretty ?

In case, to delete a specific line, you would also have to forecer the id table, but still would continue to be many instructions. At the moment I do not know why you are working with a field serialized, but it is not usually recommended to work with fields of this type, as they are difficult to handle, and it forces us to create too many routines.

  • Hello friend from what I understood in this script Voce made an unserialize that was to separate the 1052 array plus what I wanted to do the procedure to delete only this 1052 something DELETE FROM.....

  • After separating the array 1052, you must make a UPDATE with the new value, so that the value of the first line is modified.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.