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)){
$cnt++;
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 for diafol

$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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.