【问题标题】:connection results (multiple tables) php, mysqli INNER JOIN连接结果(多表) php, mysqli INNER JOIN
【发布时间】:2012-08-14 13:38:40
【问题描述】:

(在每个结果中包含多对多结果的最佳做法?)

每个帖子都有许多资源。我试图向他们展示。 它单独工作,如下所示:

资源和帖子之间的所有连接:

   $result = $mysqli->query("SELECT *
        FROM kopplaKontorsplatsResurser
        INNER JOIN resurser
        ON kopplaKontorsplatsResurser.resurs_id=resurser.id
        ");

    $num_results = mysqli_num_rows($result);
    for($i=0; $i<$num_results; $i++) {
    $row = $result->fetch_array(MYSQLI_ASSOC);
    echo 'Resource with id: '.$row[resurs_id];
    echo '<br>';
    echo 'Is connected to the post: '.$row[kontorsplats_id];
    echo '<br>';
    echo 'What resource is this? '.$row[resurs];;
    echo '<br><br>';
    }

这是我获取每个帖子信息的方式(kontorsplats)

  $result = $mysqli->query("SELECT *
                 FROM kontorsplatser
                 INNER JOIN geo_orter
                 ON kontorsplatser.ort_id=geo_orter.ort_id
                 ");
    $num_results = mysqli_num_rows($result);

    for($i=0; $i<$num_results; $i++) {
    $row = $result->fetch_array(MYSQLI_ASSOC);

    echo '<div class="kontorsplats">';
    $arbetsplatsensID = $row[id];
    $rubriken = $row[rubrik];
    $ort_id = $row[ort_id];
    $ort = $row[ortnamn];

    echo '<h4>'.$rubriken.'</h4>';
    echo '<h5><a href="">'.$ort.'</a></h5>';

       ---> Show the connected resources here. :D <------

    echo '</div>';

我正在考虑创建一个包含所有资源及其连接的数组,并为每个 div 循环遍历它,但这会是最有效的方式吗?

有趣的是包含别名: devshed

【问题讨论】:

    标签: mysqli inner-join


    【解决方案1】:

    我是这样解决的,还是有一种挥之不去的感觉,不是最优的,但是可以的!

    首先将所有连接和资源保存到一个数组中

        $result = $mysqli->query("SELECT *
            FROM kopplaKontorsplatsResurser
            INNER JOIN resurser
            ON kopplaKontorsplatsResurser.resurs_id=resurser.id
            ");
        $num_results = mysqli_num_rows($result);
        for($i=0; $i<$num_results; $i++) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
    
            $dennaKontorsplats = $row[kontorsplats_id];
            $resursens_id = $row[resurs_id];
            $resurskopplingar[$dennaKontorsplats][$resursens_id] = $row[resurs];
        }
    

    然后为每个帖子循环遍历它

    //Leta upp alla resurskopplingar: 
        foreach ($resurskopplingar as $kontoretsid => $lvl1) {
            if($arbetsplatsensID == $kontoretsid){
            foreach ($lvl1 as $lvl2) {
                echo $lvl2;
            }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多