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?
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.
We can use array element in the WHERE clause as the condition to filter the rows.
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.
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.
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);
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With