Select record that contains result equivalent to a variable

Asked

Viewed 35 times

1

I have a column in my mysql table, in which it is called "positions", where several values in int are placed there, however, with the "|" of division.

Example: 8|19|10|20|

And each number represents a category.

I would like to make a SELECT where I have only one number, I would select the records that have this number in the middle.

Example: I chose number 8 to select from the table, where my column positions is equal to 8|19|10|20|, as it has the number 8, it will return positively.

<?php
$id = isset($_GET['id']) ? $_GET['id'] : ''; // numero que vou selecionar
$sql = mysql_query("SELECT * FROM usuarios WHERE cargos LIKE '%$id%' OR cargos = '$id' ORDER BY id");
while($ver = mysql_fetch_array($sql)){

?>

I tried to do it this way, but it didn’t work with "LIKE".

  • I believe that the ideal is to completely reformulate the database, it makes no sense to store several values in a single column. The database supports several tables, it would be much easier and faster if you created a table "positions". There is a way to solve the problem, but that doesn’t seem like a good idea.

  • Look, are you sure it’s not working ? sqlfiddle .... Of course report example cargos = "4" will not work, have to use the LIKE

1 answer

0

As our friend @Inkeliz mentioned, the ideal is to reformulate the database and create a table to associate the job with the user. But if you can’t do this rewrite, you can circumvent this problem as follows:

$sql = mysql_query("SELECT * FROM usuarios WHERE (cargos LIKE '%|$id|%' OR cargos LIKE '%|$id' OR cargos LIKE '$id|%') ORDER BY id");

The problem of doing so is that you will lose the speed of consultation.

Browser other questions tagged

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