Double while loop with sql query

时间:2017-04-06 17:17:19

标签: php mysql sql while-loop

I created a code that is working fine but I'm not sure if its 'legit'. I am using a sql query in a while loop from another sql query, that means that the (second) sql query is repeated the amount of rows the first query returns.

Can anyone tell me if I can use this or its just one complete mess?

the code:

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql_feat = 'SELECT * FROM wp_wpl_dbst WHERE category = 105';
$result_feat = mysqli_query($conn, $sql_feat);

if (mysqli_num_rows($result_feat) > 0) {

    while($row = mysqli_fetch_assoc($result_feat)) {

        $filter_feat = $row["table_column"];
        $filter_name = $row["name"];

        $sql_feat2 = 'SELECT * FROM wp_wpl_properties';
        $result_feat2 = mysqli_query($conn, $sql_feat2);

        if (mysqli_num_rows($result_feat2) > 0) {

            while($row2 = mysqli_fetch_assoc($result_feat2)) {

                if (!empty($row2[$filter_feat])) {
                    echo $filter_name;
                    echo "<br>";                                         
                } 
            }
        }                                                          
    }
}

mysqli_close($conn); 

2 个答案:

答案 0 :(得分:0)

首先,在假设它代表正确的查询结果之前,你应该总是检查mysqli_query的结果:

// you should check if this value is FALSE before using it
$result_feat = mysqli_query($conn, $sql_feat);

// and this too
$result_feat2 = mysqli_query($conn, $sql_feat2);

至于在循环中运行查询的代码,除非没有其他选项,否则几乎总是不鼓励。在循环中运行任何查询之前,您应该探索JOIN的可能性。在您没有其他选项的情况下可能存在这种情况,但在您的代码中,我一点都不看到一遍又一遍地运行此查询:

$sql_feat2 = 'SELECT * FROM wp_wpl_properties';

如果它引用了$ row的值,那么也许。但它没有。

答案 1 :(得分:0)

基本上你是在做动态sql所以加入是不可能的,但是在第二次选择中添加where子句会使它更有效率。类似于 - $ sql_feat2 =&#39; SELECT&#39; + $ filter_name +&#39;来自wp_wpl_properties其中&#39; + $ row2 [$ filter_feat] +&#39;不是空的&#39;;