1

When you need to do something like this:

SELECT * FROM userinfo WHERE id in (18,2,6,4,5)

And the id array comes from another query like:

$ids = $conn->fetchAll('SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');

If I need to parse the array in order to give the right format to the query id do:

    $norm_ids = '(';
    foreach ($ids as $ids) {
        $norm_ids .= $ids['origin'] .',';
    }
    $norm_ids = substr_replace($norm_ids ,"",-1) .')';

That outputs the ids like: (id1,id2,id3,id.......), so the I'll just: FROM userinfo WHERE id in ". $norm_ids;

But seems to ugly to me, is there a way to do this better?

0

4 Answers 4

3

You could do:

$idStr = rtrim(str_repeat('?,', count($ids), ',');
$query = 'SELECT * FROM userinfo WHERE id in (' . $idStr . ')';

and then use prepare():

$conn = $db->prepare($query);
$conn->execute($ids);
$res = $conn->fetchAll(...);
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT * FROM user_info WHERE id IN (SELECT origin from action ......) ....

Comments

1

Do you need the id's separate or can you combine them into 1 query?

perhaps something like:

SELECT * FROM userinfo WHERE id in (SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');  

this way you let the sql server do the work.

Comments

1

When i am faced with such situations, i use trim

$norm_ids_str = '';
foreach ($ids as $ids) {
    $norm_ids_str .= $ids['origin'] .',';
}
$norm_ids = '(' . trim($norm_ids_str, ',') . ')';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.