Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

php - MySQL PDO query LIKE with PIPES

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...