0

Hi everyone (hope the title is right, my english is rusted sometimes)

I did a search function, it work for my "code" infos, my company names, but i need to search for email, that are in a json entry, i did it like this :

    $sql = 'SELECT SQL_CALC_FOUND_ROWS * FROM ' . $this->table . ' AS s 
            WHERE ((s.code LIKE :q)
            OR (s.company_name LIKE :q)
            OR (JSON_EXTRACT(s.contacts, "$.email") LIKE :q))';

Where is my mistake?

5
  • 2
    Well, can you share example data of the JSON? One row should be sufficient, you can mask the real values, it's the structure that matters. Commented Nov 24, 2020 at 13:59
  • sure, [{"lastname":"Bonnot","firstname":"Jean","email":"[email protected]","phone1":"0675421357"}] Commented Nov 24, 2020 at 14:24
  • 3
    I think it's failing because your JSON is in an array and not at the "top" level which $.email looks for Commented Nov 24, 2020 at 14:54
  • ok so my email is in the 2nd level, how do i do? maybe i should do a foreach of my "s.contacts" ? Commented Nov 24, 2020 at 15:02
  • 2
    Seems like contacts really ought to be another table. Would save you a lot of headaches like this one. Commented Nov 24, 2020 at 15:05

1 Answer 1

1

Ok, so i used this answer :

OR (JSON_EXTRACT(s.contacts, "$**.email") LIKE :q))';

Like @dazed-and-confused pointed my email wasn't at the top level, so i used ** to go to the 2nd level, and it work.

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

3 Comments

The only thing with this solution is that if the JSON string contains multiple arrays, this method will get all of them that match, not just one.
can't think of another way to do it, any suggestion?
OR (JSON_EXTRACT(s.contacts, "$[0].email") LIKE :q))';

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.