Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add quotation marks to comma delimited string in PHP

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')
like image 570
Per Avatar asked Oct 07 '12 20:10

Per


3 Answers

Here is what I used:

WHERE  column IN ('".str_replace(",", "','", $_GET[stringlist])."')
like image 139
boltous Avatar answered Oct 24 '22 06:10

boltous


If $variable = "option1,option2,option3"

you can use:

"SELECT * FROM TABLE WHERE FIND_IN_SET(some_column, '$variable')"

like image 37
Luke Wenke Avatar answered Oct 24 '22 05:10

Luke Wenke


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) . "') ";
}
like image 13
JRL Avatar answered Oct 24 '22 06:10

JRL