dptn69182 2016-04-14 07:14
浏览 30
已采纳

从数据库中获取和显示组作为菜单链接

First I want to say that I'm not sure that this is the proper way doing this so if there is better way please tell me.

I have input form with few dropdown and checkboxes on it. I want admin to have access to them via backend and to be able to edit/delete/create new.

I have made table in database form_field with field_id, field_name and group_id. group_id is where I store for which dropdown menu are this fields. For example dropdown Category with select options: Category_1, Category_2...Category_n. In database table will be:

field_id    field_name    group_id
   1        Category_1       1
   2        Category_2       1
   3        Category_n       1

Next dropdown on the page will be group_id=2.. Now I want to put them on the admin page like:

Manage "Category"
Manage "Some other dropdown group"
etc

How to loop the table so the name Manage "Category" to be link and take group_id=1, next will be Manage "Some other dropdown group" group_id=2 ... etc. Here is what I thought it will be but it is showing me only the first group because this is the condition..

    $sql = $pdo->prepare("SELECT * FROM form_fields");  
    $sql->execute(); 
    $row = $sql->fetch();                       

    if($row['group_id'] == 1){
            echo '<li><a href="drops.php?group_id='.$row['group_id'].'"><i class="fa fa-angle-double-right"></i> Manage "Category_1"</a></li>';
    } elseif($row['group_id'] == 2) {
            echo '<li><a href="drops.php?group_id='.$row['group_id'].'"><i class="fa fa-angle-double-right"></i> Manage "Category_2"</a></li>';
    } elseif($row['group_id'] == 3) {
            echo '<li><a href="drops.php?group_id='.$row['group_id'].'"><i class="fa fa-angle-double-right"></i> Manage "Category_3"</a></li>';
    } elseif($row['group_id'] == 4) {
            echo '<li><a href="drops.php?group_id='.$row['group_id'].'"><i class="fa fa-angle-double-right"></i> Manage "Category_4"</a></li>';
    }

Looks something simple but I'm stuck with this..

  • 写回答

1条回答 默认 最新

  • dongtaochan0777 2016-04-14 07:30
    关注

    You are selecting all from the table so you will be getting back multiple rows. For that you will need to loop through the rows like so:

    <?php
    
    $sql = $pdo->prepare("SELECT * FROM form_fields");  
    $sql->execute();
    $rows = $sql->fetch();
    
    $html = [];
    foreach ($rows as $row) {
        $html []= '<li><a href="drops.php?group_id='.$row['group_id'].'"><i class="fa fa-angle-double-right"></i> Manage "' . $row['field_name'] . '"</a></li>';
    }
    echo join("", $html);
    
    ?>
    

    Hope this is sort of what you are looking for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?