选择使用具有多个ID的php变量

I have a PHP variable that looks like this for example:

$list = "12|421|466|501|1042|"

What I wanna do is to match each number with a field in my database table.

SELECT * FROM tableName WHERE id = any of the numbers in $list

Which is the simplest way to do this?

use replace to replace | into comma and remove the last | so that you could get the string in
correct format

$list = str_replace('|',',',$list);
$query = "select * from table where ID in ($list)";
SELECT * FROM table WHERE id LIKE '%$list%'

not so sure | is a good seperator. maybe u should try setting it into an array.

guy below got it!!!

Use this SQL:

SELECT * FROM tableName WHERE id IN (12, 431, 466, 501, 1042)

Use explode(), implode() to convert your list to a comma separated list.

Use IN like this:

"SELECT * FROM tableName WHERE id IN (".str_replace('|', ',', substr($list, 0, -1)).")"

This should work:

<?php
$list = "12|421|466|501|1042|";
$items = array_filter( 
     array_map( 'trim', explode( "|", $list ) ),
     function( $item ) {
         return $item != ''; // filter empty values.
     }
);
$query = 'SELECT foo FROM bar WHERE id IN ( ' . implode( ', ', $items ) . ' );';
echo $query;

if you wan the combined result you can use IN statement like:

SELECT * FROM tableName WHERE id IN ( $cat = str_replace("|", "," , $list) )

Or if you want the separate results you have to iterate through all the values.

$array = preg_split( "\\|" , $list );
foreach ($array as $value) {
    SELECT * FROM tableName WHERE id = $value
}

SELECT * FROM tableName WHERE id IN ('.str_replace('|',',',$list).');

it will repalce all | with , and then you can run query with IN condition to get desired records..