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.

6 Years
Discussion Span
Last Post by adamworld

$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()
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.