P. Nick
P. Nick

Reputation: 991

Use exploded variable in query without having to loop

How can I run a query with multiple where clauses depending on an exploded variable (array)?

$original = "123,44,55,66";
$exploded = explode(",", $original);
foreach($exploded as $var)
{
    $query = $mysqli->query("SELECT name FROM my_table WHERE id = $var");
}

I don't want to use a foreach loop for the query itself because it uses a lot of resources and slows the loading time for the page by a lot, so how can this be accomplished?

Upvotes: 0

Views: 38

Answers (2)

Sonali Hajarnis
Sonali Hajarnis

Reputation: 187

You can check by in query so you will get result without foreach loop

Query:

$mysqli->query("SELECT name FROM my_table WHERE id in (123,44,55,66) ");

Upvotes: 3

Yash Parekh
Yash Parekh

Reputation: 1529

As per your code, every time your query gets overwrite and thus you'll get the last selected data. You can get the result by using IN operator.
Instead, try this :-

$original = "123,44,55,66";
$query = $mysqli->query("SELECT name FROM my_table WHERE id in ($original)");

Upvotes: 3

Related Questions