简体   繁体   中英

Php loop all result in next mysql query

i have a small problem. I use two mysql queries for getting data. First i want to get IDs from groups

$sqlGoups = "SELECT * from `groups` WHERE `Date`='$TodayDate' ";
$result = $conn->query($sqlGoups);
if ($result->num_rows > 0) {
      while($row = $result->fetch_assoc()) {
    $IDgroups = $row["ID"]; 

With that, I'll get those IDs, for example 5, 7, 12, 15, 22

I want to put them all in the next mysql query:

 $sqlNext = "SELECT * FROM `orders` WHERE ID = '$IDgroups' ORDER BY `ID` ASC ";
$result = $conn->query($sqlNext);

When I do this, I get the result only for the first ID (5). And I want for each

I can not INNER JOIN tables because I use this in next query.

I tried with foreach loop, but no effect.

Try this code

SELECT * FROM `orders` 
WHERE ID  REGEXP CONCAT('(^|,)(', REPLACE('$IDgroups', ',', '|'), ')(,|$)') 
ORDER BY `ID` ASC 

Just like @Elanochecer commented the best bet should be a JOIN statement, but if you wish to go through your route, you could use the IN and provide the IDs as comma separated string, your query should look similar to the one below:

... $sqlNext = "SELECT * FROM orders WHERE ID IN ('$IDgroups') ORDER BY ID ASC "; ...

Also, confirm if $IDgroups is in the format 1,2,3,4

If you provide the schema I could come up with a workable JOIN statement for you, preferably you can create a repo with the schema

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