10

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')
Per
  • 149
  • 2
  • 4
  • 12

5 Answers5

14

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) . "') ";
}
JRL
  • 76,767
  • 18
  • 98
  • 146
  • What I mean by "feels wrong" is that there might be a bitter way :) Do you think this function will do it faster? – Per Oct 07 '12 at 20:55
4

If $variable = "option1,option2,option3"

you can use:

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

Luke Wenke
  • 1,149
  • 2
  • 23
  • 43
3

we know that implode converts array to string,we need to provide the separator and then array as shown below, here we have (coma ,) as a separator. Implode breaks each element of an array with the given separator,I have conceited '(single quotes) with the separator.

 $arr = array();
    $arr[] = "raam"; 
    $arr[] = "laxman"; 
    $arr[] = "Bharat"; 
    $arr[] = "Arjun"; 
    $arr[] = "Dhavel"; 
    var_dump($arr);


    $str = "'".implode("','", $arr)."'";
    echo $str;

output: 'raam','laxman','Bharat','Arjun','Dhavel'

Hardik Vyas
  • 500
  • 1
  • 7
  • 27
  • While this may answer the question it’s always a good idea to put some text in your answer to explain what you're doing. Read [how to write a good answer](http://stackoverflow.com/help/how-to-answer). – Jørgen R Mar 04 '15 at 07:38
2

Here is what I used:

WHERE  column IN ('".str_replace(",", "','", $_GET[stringlist])."')
Rey Libutan
  • 5,226
  • 9
  • 42
  • 73
boltous
  • 31
  • 1
-1

There is only one correct way to escape strings for SQL - use the function provided by the database api to escape strings for SQL. While mysyl_* provides mysql_real_escape_string():

$choices = explode(",", $variable);

foreach($choices as &$choice)
    $choice = "'".mysql_real_escape_string($choice)."'";

$choices = implode(",", $choices);

PDO provides a method that will add quotes at the same time:

$choices = explode(",", $variable);

foreach($choices as &$choice)
    $choice = $pdoDb->quote($choice);

$choices = implode(",", $choices);

Note that PDO::prepare doesn't really work here

Community
  • 1
  • 1
Eric
  • 95,302
  • 53
  • 242
  • 374