如何从第一个选择查询中获取两个id,然后将其用于第二个选择查询?

时间:2015-05-08 11:10:50

标签: php

我使用下面的代码



<?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 />";
    }
}
?>
&#13;
&#13;
&#13;

我得到两个mon_id,如12 接下来我想在第二个mon_id中使用这两个select query,但第二个查询只给我一个结果意味着只给result one name。 我怎样才能获得2nd name

2 个答案:

答案 0 :(得分:-1)

首先:通过将查询组合到一个查询中,可以实现所需的结果 有很多方法可以让它更快,但在你的情况下,最容易理解的查询如下所示:

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

您不会从状态表中获取任何数据,但由于您只对监视器查询的mon_id感兴趣,因此无关紧要。

第二:你应该看看MySQL中的JOIN查询

第三:您必须查看转义字符串的查询,一个好主意是使用绑定变量和PDO:良好的开端是http://www.w3schools.com/php/php_mysql_prepared_statements.asp

答案 1 :(得分:-1)

您在第二个查询中覆盖了$result变量,从而丢失了第一个查询中的数据。更改第二个查询变量的名称,您已完成。

<?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
    }
}
?>