I am having a bit of a problem running a select query on a database. Some of the data is held as a list of comma separated values, an example:
Table: example_tbl
| Id | People | Children |
| 1 | 1,2,3 | 8,10,3 |
| 2 | 7,6,12 | 18,19,2 |
And an example of the kind of thing I am trying to run:
<?php
include 'class.php';
$selection = 1;
$db = new DbClass;
$tbl_name = 'example_tbl';
$sql = "SELECT * FROM $tbl_name WHERE ".$selection." IN People";
$result = $db->query($sql);
$print_r($result);
?>
The script above should return row 1 after finding a '1' in the People column but clearly I have mucked it up.
The issue I am having is that I think I have the IN statement backwards, i.e. I THINK this method would be to select values if $selection was a comma separated (imploded) list, rather than the way round I am trying to use it.
I don't know if it's too important about what I am sending and receiving from the db class above, but if you wanted to know, it's just a simple script that runs all relevant bits and returns an array of the result. at the moment it's returning nothing because it's not finding a match
Thanks in advance for anything you can tell me.
Cheers -Dave
Why do people insist on this insane habit of comma-separated data values in a column rather than properly normalising their database design. It always leads to problems.
SELECT *
FROM $tbl_name
WHERE CONCAT(',',People,',') LIKE '%,".$selection.",%'";
or
SELECT *
FROM $tbl_name
WHERE FIND_IN_SET(".$selection.",People);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With