0

I have a database having a filed myfield containing json string:["2","4","1","6"] OR ["1"] . I want to make a filter for this filed and was thinking to query it with:

SELECT id FROM table_name WHERE myfield = '5' -> this return can not echo id because ["2","4","1","6"] does not have the value 5.

SELECT id FROM table_name WHERE myfield = '1' -> return can echo id-> because -> in json string on filed myfield have the value 1.

how can fix it? what do i do?

I tried as but it don't work for me:

SELECT id FROM table_name WHERE myfield = '1'

3 Answers 3

1

To check for id=1 for instance you can do

SELECT 1 as id
FROM table_name 
WHERE find_in_set('1', replace(myfield, '"', '')) > 0

You can use it like this in your code

$this->db->query("SELECT 1 as id 
                  FROM table_name 
                  WHERE find_in_set('1', replace(myfield, '\"', '')) > 0");
Sign up to request clarification or add additional context in comments.

8 Comments

I use it on codeigniter as: $row = $this->db->query('SELECT id FROM table_name WHERE find_in_set(5, replace(myfield, '"', '')) > 0')->row(); and echo result as: echo $row->fieldname; and getting this error:Parse error: syntax error, unexpected '1' (T_LNUMBER) what do i do?
I don't know. I see no 1 in your query. Do you have an id column in your table?
BTW you should delimit your strings with " instead of ': $row = $this->db->query("SELECT...
Delimit your query with " as I said. If you don't then you will end the query with the next '
I use of " it interferes with ..., '"', ... and have error: Parse error: syntax error, unexpected '', '' (T_CONSTANT_ENCAPSED_STRING)????
|
0

The given solution by @juergen will not work if you search first or last item . For this you need to replace square brackets also . This worked for me

SELECT * 
FROM `tbl_tasks_weekly` 
WHERE FIND_IN_SET('1', REPLACE( REPLACE( REPLACE(`myfield`,']','') ,  '[',''),'\"','')) 

Comments

0

Use serialization and deserialization to save or retrieve data from database field.

Comments

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.