Reputation: 61
I have a Array named $category
which has values in string format.
I want to add it in query such that I can filter the results by category.
Something Like this:
SELECT * FROM ig_accounts WHERE category IN (Array Values here)
So the query becomes something like:
SELECT * FROM ig_accounts WHERE category IN ('text','fashion','sports')
Right now I am using this, which has an error:
$query = "SELECT * FROM ig_accounts WHERE category IN (".
for($i=0;$i<$category[NULL];$i++)
{
echo '$category[$i]';
}
.")";
Upvotes: 0
Views: 199
Reputation: 26281
Is $category
provided by the user? If so, beware, and consider prepared statements. Try the following.
$sql='SELECT * FROM ig_accounts WHERE category IN ('.implode(',', array_fill(0,count($category ), '?')).')';
$stmt=$myDB->prepare($sql);
$stmt->execute($category );
Reference http://php.net/manual/en/book.pdo.php
Upvotes: 1
Reputation: 9583
Use join
to make the string from an array. This is the way how can you do the thing.
$arr = array();
for($i = 0; $i < count($category); $i++){
$arr[] = $category[$i];
}
$in = join(" , ", $arr);
$query = "SELECT * FROM ig_accounts WHERE category IN (".$in.")";
Upvotes: 0
Reputation: 638
You can do something like this
$query = "SELECT * FROM ig_accounts WHERE category IN ('" . implode("','", $category) . "')";
http://php.net/manual/en/function.implode.php implode — Join array elements with a string
<?php
$a1 = array("1","2","3");
echo "a1 is: '".implode("','",$a1)."'<br>";
?>
will produce:
===========
a1 is: '1','2','3'
Upvotes: 1
Reputation: 2595
You can use the implode function depending on the structure of your array
http://php.net/manual/fr/function.implode.php
$query = "SELECT * FROM ig_accounts WHERE category IN ('" . implode("','", $category) . "')";
Upvotes: 4