0

I have a lot of bad data in a table and was hoping there's a query I can use to edit this data.

[{"type":"user","id":"584851"},"2":{"type":"user","id":"180269"},"3":{"type":"user","id":"140535"}]

and here's how I need it to look...

[{"type":"user","id":"584851"},{"type":"user","id":"180269"},{"type":"user","id":"140535"}]

So basically removing all occurrences of ' "2": ' (the number will differ)

Is there a simple query to do this or will I need to write something in php to do the job?

1
  • 1
    MySQL doesn't bundle a regex replace function. You'll have to use some user-edfined function for the same if you have privileges. github.com/hholzgra/mysql-udf-regexp Commented Sep 16, 2015 at 10:16

1 Answer 1

1

Unfortunately, MySQL does not have a REGEX_REPLACE function or equivalent that would let you run a simple update query. The next best thing I would suggest is to loop through every record in your table using your language of choice and applying the regex replace on it and saving. I have put an example in PHP below:

$db = new PDO(sprintf('mysql:host=%s;dbname=%s', $host, $dbname), $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = $db->query('select * from `table`');

foreach ($query->fetch(PDO::FETCH_OBJ) as $row) {

    $update = $db->prepare('update `table` set `data` = ? where `id` = ?');
    $update->execute([
        preg_replace('/"\d+":{/', '', $row->data),
        $row->id
    ]);
}

Assumptions have been made about your table structure but the important part of the code is the preg_replace parameter which will match what you need to remove.

Sign up to request clarification or add additional context in comments.

2 Comments

MariaDB does have such a function.
I answered with the assumption that he only has MySQL and does not want to, or cannot, mess around with the database server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.