简体   繁体   中英

how can i get two id from 1st select query and then use this to 2nd select query?

I'm using below code

 <?php $site_id = '7AF099D94576F8C4'; // Check Monitor ID from site id $sql = "SELECT * FROM status Where site_id='$site_id'"; $result = $conn->query($sql); while ($row = $result->fetch_assoc()) { $st_id = $row['st_id']; $mon_id = $row['mon_id']; $mon_site_id = $row['mon_site_id']; echo $mon_id; $result = mysql_query("SELECT * FROM monitors WHERE mon_id='$mon_id'") or die(mysql_error()); // keeps getting the next row until there are no more to get while ($row = mysql_fetch_array($result)) { // Print out the contents of each row echo $row['name'] . "<br />"; } } ?> 

And I'm getting two mon_id like as 1 and 2 so next I want to use these two mon_id in 2nd select query but 2nd query give me just one result mean give result just one name . How can I get 2nd name ?

First: your desired result can be achieved by combining the queries into one query.
There are tons of ways to get it faster, but in your case the most understandable query looks like this:

SELECT * FROM monitors WHERE mon_id IN ( "SELECT mon_id FROM status Where site_id='$site_id'");`

You will not get any data from your status table, but as you are only interested in the mon_id for your monitors query, that will not matter much.

Second: you should take a look at JOIN Queries in MySQL

Third: you must have a look into escaping strings for queries, a good idea is to used bound variables and PDO: a good start is http://www.w3schools.com/php/php_mysql_prepared_statements.asp

You are overwriting your $result variable in your second query, thus losing the data from your first query. Change the names for the second query variables and you're done.

<?php
$site_id = '7AF099D94576F8C4';
// Check Monitor ID from site id
$sql = "SELECT * FROM status Where site_id='$site_id'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
    $st_id = $row['st_id'];
    $mon_id = $row['mon_id'];
    $mon_site_id = $row['mon_site_id'];
    echo $mon_id;

    /// CHANGE HERE
    $result2 = mysql_query("SELECT * FROM monitors WHERE mon_id='$mon_id'") or die(mysql_error()); 
    /// CHANGE HERE 

    // keeps getting the next row until there are no more to get

    /// CHANGE HERE
    while($row2 = mysql_fetch_array( $result2 )) {
    /// CHANGE HERE
        // Print out the contents of each row
    /// CHANGE HERE
        echo $row2['name']."<br />";
    /// CHANGE HERE
    }
}
?>

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