Question

I want to pass a string that contains many usernames, seperated by a comma,and want to pass it to query

   $name_list='kesong,nicholas,jane';   //this value would change
$select_occupy=mysql_query("SELECT * FROM user_data WHERE `username` IN('$name_list') ORDER BY `occupy_date` ");// i think this would just search for a username which is 'kesong,nicholas,jane', instead searching them seperately
    echo mysql_num_rows($select_occupy); //would echo 0

I know it works only when you specify like IN('$name1','$name2','$name3'), but I need a dynamic one

No correct solution

OTHER TIPS

As a suggestion, just hold your names into an array and do like below:

$names=array('name1','name2','name3');
$namesToCheck="";
foreach($names as $name){
    $namesToCheck.="'$name',";
}
//to remove the last ,
$namesToCheck=substr($namesToCheck,0,-1);

Now, you can put $namesToCheck into your IN query.

EDIT:

In this answer, this is assumed that you will prevent any possible SQL injections as current answer is just an idea about your question. The minimum suggestion to perform preventing SQL injections would be using mysql_real_escape_string function, which escapes special characters in a string for use in an SQL statement. For example:

$namesToCheck.="'".mysql_real_escape_string($name)."',";
//OR DO THIS ON FINAL STRING

NOTE THAT This extension is deprecated as of PHP 5.5.0. You can take a look at the PHP's official document in the following link:

mysql_real_escape_string

You can do it like this :

    $namesToCheck = "'" .implode( "','" ,explode( ',' ,$name_list ) ) ."'";

And then use the $namesToCheck in the IN clause of your query .

The above code would convert :

    kesong,nicholas,jane

to :

    'kesong','nicholas','jane'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top