Problem in PHP+Mysql query using LIKE

Asked

Viewed 260 times

1

Good afternoon guys, recently in one of my projects a problem arose and I hope you can help me.

To better understand the site is a site of consultations in the area of health, as clinics, cardiology, urology, etc. Some clinics may belong to two categories at the same time, as "Clinic" and "Cardiology" I made the consultation as follows:

$url.= ' AND t.areadasaude LIKE "%'.$especialidadesaude.'%"';

The problem is, the Cardiology category belongs to id = 1, cardiology belongs to id = 19, as the LIKE refers to everything that is within the table all results that are within category 19 are appearing in category 1 because the LIKE takes id number 1 19. How I make LIKE take 100% of what is marked?

Note: If I mark two categories, the database is recorded as follows: ["1","19"], we should consider in consultation tbm when there is more than one category marked. Someone could help me?

  • 1

    Like it’s not for that.

3 answers

2

how about using t.areadasaude IN ('1', '19') instead of LIKE

  • I cannot fix the exact values because it is a query with various categories, either 1, as 2, 5, 10, or ["10","20"] =/ the values 1 and 19 was only figurative

  • I understand that can not be fixed, I just gave an example of IN. In this case you have to do something in your code that takes these values and puts them in an already formatted variable to use in IN().

0

$tab_consul[0] = "10";
$tab_consul[1] = "8";
$tab_consul[2] = "14";

// Collar tudo junto, com "," entre os dados
$string_in = implode(",",$tab_consul);
// Uso de IN para ter os valores de areadasaude que estão na lista
$url.= ' AND t.areadasaude IN(".$string_in.")";

0

What value comes in this variable $especialidadesaude and how is it stored in this field 'areasaude'? If it’s space-separated ids (or another character) you can use slipt:

$ids = split(' ', $especialidadesaude);

could return the field values in the database, if they are stored separated by a comma tmb and split it and compare the vectors;

If the field areasaude in the database has only one value the query would look like this:

$url.= ' AND t.areadasaude IN($ids)';

But if the ids of the related categories are being stored in a field I believe that this is not ideal but rather have a relationship n:m where there would be a table with the ids of the two tables. In this case the query would look like this (I did not test the query):

SELECT c.* FROM categorias c 
INNER JOIN clinicas_x_categorias cxc ON c.idCat = tbs.idCat
WHERE cxc.idCat IN($ids)
GROUP BY c.idCat 

Browser other questions tagged

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