简体   繁体   中英

Select from database where username = any value within an array

I have an array called $friends and it has some values

$friends = array(); $friends[0] = 'Alex'; $friends[1] = 'Jake';

I want to be-able for my SQL query to select every array value in this case it is Alex and Jake

$q = "SELECT * FROM posts WHERE username='$friends' ORDER BY id DESC";

But I can't do that, I get a message saying "Notice: Array to string conversion in".

Please help I am quite new to PHP

Use implode make the array into a string with the values and use IN for lists in MySQL.

$friends = array('Alex','Jake');
$str     = implode ("', '", $friends);
$q       = "SELECT * FROM posts WHERE username IN ('". $str . "') ORDER BY id DESC";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM