简体   繁体   中英

checking for the existence of a word a mysql row(php)

i have a mysql table users like this:

id      username     following
15      one          ,13,14,16,17,
14      two          ,76,43,13,
13      three        null

now three has 0 following and 2 followers. and i want a query to check for all users who have ,13, in the following row

Something like this:

$query = mysql_query('SELECT * FROM users WHERE following has ",13,"');

but works.

I can select all the following of each user and do this:

if (strpos($result_from_query,',13,') !== false) {
    echo $fetch['username'];
}

I would use IN for greater flexibility if the value in the following column is an array .

SELECT * 
FROM `users` 
WHERE `following` IN(13)

Have you tried using LIKE ?

$query = mysql_query('SELECT * FROM users WHERE following LIKE "%,13,%"');

The % characters before and after the ,13, string act as a wildcard allowing any characters to be there, so will find ,13, in any position in the string.

Also, as an aside, @Jay Blanchard has suggested using the IN operator ( in his answer )

Assuming that the numbers always have starting and trailing commas you can use:

$query = mysql_query('SELECT * FROM users WHERE following LIKE "%,13,%"');

Please read up on LIKE statements for more info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM