mysql WHERE IN array string / username

Viewed 82431

Code:

$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142");
$friendsArray2 = join(', ',$friendsArray);  
$query120 = "SELECT picturemedium FROM users WHERE username IN ('$friendsArray2')";
echo $query120;

This is the output :

SELECT picturemedium FROM users WHERE username IN ('zac1987, peter, micellelimmeizheng1152013142')

It fails because usernames are not wrapped by single quotes like 'zac1987', 'peter', 'mice...'. How can each username be wrapped with single quotes?

6 Answers

When using "IN" logical operator with strings, each string should be wrapped with quotation marks. This is not necessary if all values are numeric values.

$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142");
$friendsArray2 = join("','",$friendsArray);  
$query120 = "SELECT picturemedium FROM users WHERE username IN ('{$friendsArray2}')";
echo $query120;

The output should be :

SELECT picturemedium FROM users WHERE username IN ('zac1987','peter','micellelimmeizheng1152013142')
Related