duanlinma5885 2017-04-06 17:17
浏览 38

使用sql查询双循环

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条回答 默认 最新

  • dongtang2376 2017-04-06 17:25
    关注

    First, you should always check the result of mysqli_query before assuming it represents a proper query result:

    // 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);
    

    As for your code running a query inside the loop, it is pretty much always discouraged unless there is no other option. You should explore the possibility of a JOIN before running any queries inside a loop. Cases may exist where you have no other option, but in your code, I don't see any point at all to run this query over and over:

    $sql_feat2 = 'SELECT * FROM wp_wpl_properties';
    

    If it made reference to the value from $row, then maybe. But it doesn't.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配