3

$color is array

$sql=" SELECT * FROM products  WHERE color IN (".implode(',', $color).")";

its showing result is

SELECT * FROM products WHERE color IN (red,green,blue);
SELECT * FROM products WHERE color IN ('red','green','blue');
1
  • Use it as '".implode("','", $color)."';// output 'red','green','blue' Commented Jun 24, 2016 at 6:08

4 Answers 4

4

Update your query like as

$sql="SELECT * FROM products  WHERE color IN ('".implode("','", $color)."')";
                                           //^^         ^^  ^^          ^^ Added
Sign up to request clarification or add additional context in comments.

Comments

4

Try this:

$sql = "SELECT * FROM products  WHERE color IN ('".implode("','", $color)."')";

Comments

0

Use It like this:

 $sql = "select * from products  where color IN ('".implode("','", $color)."')";

Comments

0

While using ' around implode and "','" as a glue works like a charm in this situation you can also use array_map to surround each value of the array with ' and then implode with simple ,

$color = ['red', 'green', 'blue'];
$string = implode(
    ',',
    array_map(
        function ($value) {
            return "'{$value}'";
        },
        $color
    )
);
echo $string; // => 'red','green','blue'

It might be overkill in this case and it may be a little slower than other answers.

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.