Home > Enterprise >  How to use a string with array value in Mysql?
How to use a string with array value in Mysql?

Time:01-17

I want to select some results from my database but it must exclude the last 3 results which I got already.

The result I got already is in a string inside a foreach.

$result is a foreach string with three ID values (one for each), eg: 1, 2, and 3.

If I use $result in my query, it'll only exclude ID 3, because it's the last one.

This is what I've tried already, which works but only excludes the ID 3:

foreach ($pdo->query($sql) as $abc) {
 $result = $abc['imp'];
}
SELECT * FROM t1 INNER JOIN t2 ON t1.cat = t2.id INNER JOIN t3 ON t1.aut = t3.id WHERE t1.imp <> $result AND t1.status = 1 ORDER BY t1.pub DESC LIMIT 3

What could I do to exclude all $result instead?

CodePudding user response:

Make $result into an array. Then use them in the IN() list. You can create a list of ?,?,... of the same length to use as placeholders in the query, and use the array as the values argument to $stmt->execute()

$result = [];
foreach ($pdo->query($sql) as $abc) {
    $result[] = $abc['imp'];
}

$placeholders = implode(',', array_fill(0, count($result), '?'));

$stmt = $pdo->prepare("
    SELECT * FROM t1 
    INNER JOIN t2 ON t1.cat = t2.id 
    INNER JOIN t3 ON t1.aut = t3.id 
    WHERE t1.imp NOT IN ($placeholders)
        AND t1.status = 1 
    ORDER BY t1.pub DESC 
    LIMIT 3");
$stmt->execute($result);
  • Related