问题
I have a PDO statement which is supposed to look for data with pipes around it, I have multiple id's stored in a single column. I know this isn't great but it seems the logical way to store the data.
Column content example |1|3|4|5|14|76|
So I want to find every line in the database with 3 in it. I use a php form to post or get 3
$getthis = $_GET['getthis'];
$sql = "SELECT * FROM table WHERE types LIKE '?' ORDER BY name";
$q = $conn->prepare($sql);
$q->execute('%|$getthis|%');
while ($data = $q->fetch()) { do something }
Its not good, Ive tried various ways of doing this but I fail miserably every time.
Thanks for your help in advance and great site by the way! Its helped me loads
EDIT - Thanks for your help, I cant really change the structure unless I limit the number of sub-categories an item should be under. As this is what this column contains (so socks could be under footware[1] and footprotectors[4] and possibly 20 other subcats
Ill try this method 'find_in_set' but im confused as to why it needs to be higher than a zero?? Thanks again!
回答1:
You can use FIND_IN_SET()
SELECT * FROM table
WHERE find_in_set('$getthis', replace(types, '|', ',')) > 0
ORDER BY name
But you really should change the DB structure!
来源:https://stackoverflow.com/questions/18850372/mysql-pdo-query-like-with-pipes