Add quotation marks to comma delimited string in PHP

Per picture Per · Oct 7, 2012 · Viewed 11.9k times · Source

I have a form which is a select multiple input which POSTs values like this: option1,option2,option3 etc..

How is the best way to convert this to 'option1','option2','option3' etc...

Currenty I'm doing this, but it feels wrong??

$variable=explode(",", $variable);
$variable=implode("','", $variable);

The reason why I'm doing this is because I want to use the form select multiple inputs in a SQL Query using IN.

SELECT * FROM TABLE WHERE some_column IN ('$variable')

Answer

JRL picture JRL · Oct 7, 2012

You can wrap whatever code in a function to make the "feels wrong" feeling disapear. E.g.:

function buildSqlInClauseFromCsv($csv)
{
        return "in ('" . str_replace(",", "','", $csv) . "') ";
}