I have code where I am pulling data from my database and it needs to be separated by commas except the last value (that part works) so I can take those values and input into another SQL query. Here is the working code:

$biz_id = $row_businesses['id'];
$query_related = sprintf("SELECT * FROM related WHERE biz_id = '$biz_id'");
$related = mysql_query($query_related, $merchant_info) or die(mysql_error());
while($row = mysql_fetch_array($related)){
if($cnt!=1) echo ', ';
$ids = $row['requester_biz_id'];
echo $ids;

My issue comes in when I need those values. If I take

echo $ids

out of the last bracket, it only displays one value and not all. How do I get these values outside of that bracket so I can use them in my next query? My next query I am using

SELECT * FROM tbl_name WHERE id IN ($ids) ORDER BY RAND()

Any help would be greatly appreciated. I think this might be a simple fix but I can't seem to figure it out. Thanks.

Member Avatar

$ids in your last code is an array. $ids in your loop is a string which gets overwritten on every iteration.

Make $ids likethis:

while($row = mysql_fetch_array($related)){
   $ids[] = $row['requester_biz_id'];
echo implode(", ",$ids);

Now this should work:

SELECT * FROM tbl_name WHERE id IN ($ids) ORDER BY RAND()

That worked! Thank you for your help!