Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql WHERE IN array string / username

Tags:

arrays

php

mysql

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?

like image 726
zac1987 Avatar asked Jul 07 '11 21:07

zac1987


People also ask

How to use array in WHERE clause in MySQL?

The following is the syntax to send an array parameter with the help of where IN clause. mysql> SELECT * -> FROM PassingAnArrayDemo where id IN(1,3,6); The following is the output.

Can we use array in where clause?

We can use array element in the WHERE clause as the condition to filter the rows.

Can you use in with strings MySQL?

MySQL INSTR() functionMySQL INSTR() takes a string and a substring of it as arguments, and returns an integer which indicates the position of the first occurrence of the substring within the string.

Is there a Contains function in MySQL?

MySQL query string contains using INSTR INSTR(str, substr) function returns the index of the first occurrence of the substring passed in as parameters. Here str is the string passed in as the first argument, and substr is the substring passed in as the second argument.


2 Answers

Let's loop through each name one by one, escaping each.

I'm going to recommend that you use an actual MySQL escaping function rather than just wrapping quotes around, to ensure that the data actually goes into the query correctly. (Otherwise, if I entered a name like It's me!, the single quote would mess up the query.) I'm going to assume here that you're using PDO (which you should!), but, if not, replace references to PDO::quote with mysql_real_escape_string.

foreach($friendsArray as $key => $friend) {
  $friendsArray[$key] = PDO::quote($friend);
}

$friendsArray2 = join(', ', $friendsArray);
like image 58
Matchu Avatar answered Oct 19 '22 16:10

Matchu


If you don't want to use PDO or other complicated solutions use implode function and you are all set.

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

Solution : I just imploded your $friendArray by ',' that's it. plain and simple! and It's working.

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

like image 13
Jignesh Bhavani Avatar answered Oct 19 '22 15:10

Jignesh Bhavani