A
A
Alexey Medvedev2017-10-30 17:14:59
PHP
Alexey Medvedev, 2017-10-30 17:14:59

How to make a selection from the database for a certain category?

The essence of the question is this: there is a very old site on pehe, two tables in MySQL
table1 (goods / services)
-----------------------
| id | name | cat_id |
-----------------------
and table2 (categories themselves and category attributes)
------------------ ---------
| id | name | desc | etc. |
---------------------------
The `cat_id` field contains entries such as:

  • one
  • 12
  • 2
  • ten
  • eleven
  • 10, 11
  • 2, 11

where id categories are indicated, separated by commas. I need to select goods/services that belong to, for example, the first category.
Now, while there are no more than 20 categories, I made a quick crutch, but I urgently need a normal solution, and not this one:
$multicat = ($cat['id'] !=1 )?"(`category` REGEXP '".$cat['id']."(?=,|$)' or `category`='".$cat['id']."')":"(`category` REGEXP '".$cat['id']."(?=,)' or `category`='".$cat['id']."')";

$select = 'select `name` from `table1` where '.$multicat.' order by `id` asc');

This momentary f*ck needs to be removed urgently!
PS: all id categories separated by commas are specified in ascending order.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2017-10-30
@alexey-m-ukolov

urgently need a solution
Change the database structure. There simply cannot be another solution.

L
Lander, 2017-10-30
@usdglander

... WHERE `category_id` LIKE '%,12,%'
upd. And generally the normal decision is a normalization of a DB. Add a link table.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question