Search id returned from json_encode() inside mysql

Asked

Viewed 68 times

0

I have the following content in the field pro_are_id : ["11","3"] this content I made with json_encode(), would like to make a query to the database and know if there is this id specifically or not, I tried that way:

$area = 1;
$this->db->like("pro_are_id", $area);
return $this->db->get('produto')->result();

The problem with this method is that it will return true, because there is 11, which contains the number 1 (id I’m searching for).

What would be the right way to get the result? Since I can’t simply use WHERE?

Note: I am using codeigniter, but if the answer is in PHP, I can use within CI guidelines.

  • What if you search for the string instead of the whole search? Type $area = '"1"', looking for value "1" instead of 1.

  • @Andersoncarloswoss It would not work, when I return the query, it uses %1%, IE, it will bring this result, need in a way that returns only 1, without using the %.

  • How are you returning the value of json_encode? Because then you can recover $area->pro_are_id

  • have you thought about first returning the query without like the result of it using the array_search? http://php.net/manual/en/function.array-search.php

2 answers

0


I got the solution as follows:

$area = 1;
$this->db->like("pro_are_id", json_encode($area));
return $this->db->get('produto')->result();

Passing json_encode() by $area, returns me only if you have the record... It doesn’t seem right, but here it worked perfectly. Unless there’s another logic that works better.

  • if the field "pro_are_id" is number the ideal is to use get_where to generate the query with where pro_are_id = x and not where pro_are_id like "5". for efficiency is faster the = than the like.

-1

From what I’ve seen in the documentation, try to use:

$this->db->get_where('produto', array('pro_are_id', 1))->result();

Uncalled for $this->db->like("pro_are_id", $area);

Browser other questions tagged

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