简体   繁体   中英

multi layered mysql call within php

hope you're all looking forward to the weekend. :)

I have a slight organisational rearrangement problem with some php/mysql. I have the following piece of code which works perfectly well:

// Get the regions our user is assigned to look after
$result1 = mysqli_query($con,"SELECT * FROM regions WHERE staff_100_id='$id'");
while ($row1 = mysqli_fetch_assoc($result1)) {

    // Now get the claims that have come in for the above regions.
    $result2 = mysqli_query($con,"SELECT * FROM registrar_claims WHERE reg_region='$row1[region]' && ready_to_process='yes' ORDER BY claim_id ASC");
    while ($row2 = mysqli_fetch_assoc($result2)) {

        echo $row2[claim_id] ." ";
        echo $row2[reg_1st_name] ." ";
        echo $row2[reg_2nd_name] ."<br>";

        }
    }
}

The output of this is something like:

2 Roger Ramjet
7 Snobby Bobgrass
5 Num Nut
6 Phil Pott

I'd like to have the output come out so that it is arranged by claim_id in respect overall, not just as per cycle within the db calls. So I want the output to become:

2 Roger Ramjet
5 Num Nut
6 Phil Pott
7 Snobby Bobgrass

Would someone be willing to show me how to rearrange things to achieve this?

Thank you, very much appreciated! :)

Cass

regionI hope you are escaping your query entries :)

What I would do is compact the queries by using a subquery

SELECT * 
FROM registrar_claims 
WHERE reg_region IN (SELECT region FROM regions WHERE staff_100_id='$id') 
   AND ready_to_process='yes'
ORDER BY claim_id ASC

That should yield the desired ordered results

You could JOIN the two tables and do the whole thing in one query.

SELECT *
FROM regions JOIN registrar_claims 
ON registrar_claims.region_id=regions.region 
WHERE regions.staff_100_id='$id' && registrar_claims.ready_to_process='yes' 
ORDER BY registrar_claims.claim_id ASC

Hope this helps:

<?
// Get the regions our user is assigned to look after and all the claims that have come in 
//for the above regions.

$query = 
    "SELECT 
        regions.*,
        registrar_claims.*
    FROM 
        regions inner join registrar_claims on registrar_claims.reg_region = regions.region
    WHERE 
        regions.staff_100_id='$id' and
        registrar_claims.ready_to_process = 'yes'
    ORDER BY
        registrar_claims.claim_id";

while ($row = mysqli_fetch_assoc(mysqli_query($con, $query))) {
        echo $row[claim_id] ." ";
        echo $row[reg_1st_name] ." ";
        echo $row[reg_2nd_name] ."<br>";
}
?>

Plus I would advise looking at prepared statements for the security and clarity of your code.

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