John Smith
John Smith

Reputation: 495

Is it bad practice to execute this query in a for or foreach-loop?

So I have the following query:

$resclients=$mysqli->query("SELECT id,client_name FROM clients WHERE id IN ($result[])");

And I am wondering, is it bad practice to execute the above query in a for or foreach-loop, does it hurt the MySQL server?

Or, is it better to do LEFT JOINS or INNER JOINS or RIGHT JOINS?

Forgot to add, the $result[] is actually a two dimensional array.

Show your array:

Array
(
    [0] => Array
        (
            [id] => 7
            [resclients] => 6,7,8,9,10,11,12,13,14,15
        )

    [1] => Array
        (
            [id] => 5
            [resclients] => 5
        )

    [2] => Array
        (
            [id] => 4
            [resclients] => 4
        )
)

Just a small portion of it.

Upvotes: 0

Views: 410

Answers (1)

devpro
devpro

Reputation: 16117

You can use it as:

// a testing multidimensional array
$testArr = array(
        array(
            'one'=>1,
            'two'=>2,
            'three'=>3)
        );

$yourIds = array();
foreach ($testArr as $value) {
    foreach ($value as $finalVal) {
        $yourIds[] = $finalVal[];
    }   
}

$implodedIds = implode(",",$yourIds);
echo "SELECT id,client_name FROM clients WHERE id IN ($implodedIds)";

Result:

SELECT id,client_name FROM clients WHERE id IN (1,2,3)

Note that: this is basic idea how can you use without using query in a loop.

Upvotes: 1

Related Questions