0

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]';   
                }
                .")";
4
  • make your for loop outer of the query and format it properly. Commented May 7, 2016 at 17:47
  • 1
    Don't echo, concatenate. Use foreach to. What is $category[NULL]? Commented May 7, 2016 at 17:49
  • I have to use Loop in the Query because the values will be dynamic depending upon what Categories the User has Selected. Commented May 7, 2016 at 17:50
  • In for do $query .= also use " variables in single quotes aren't processed. Commented May 7, 2016 at 17:50

4 Answers 4

4

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) . "')";
Sign up to request clarification or add additional context in comments.

Comments

1

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'

1 Comment

you have some missing simple quote around the brackets.
1

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

Comments

0

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.")";

4 Comments

I guess this will work, In C++ i use for(i=0;i<=variable[NULL];i++) How do i specify last value in php that is NULL ?
I mean how to get size of array directly in PHP,
use count() function.
@shobhit99, I update my answer how you want it to be.

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.