dp13668681869 2014-10-17 13:01
浏览 46
已采纳

使用变量运行PHP循环

Searched for the solution- found nothing. Maybe I used the wrong terms.

I try to split the server-side operations and the html structure. So I made two different files, first the index.php and then operation.php.

Inside of the operation.php I made a mysqli query and fetched the content of an mysql table into different variables:

$query = "SELECT * FROM work";
    if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $title = $row["title"]; 
        $desc = $row["desc"];
        $id = $row["id"];
        $date = $row["date"];
        $time = $row["time"];
        $kat = $row["kat"];
        $user = $row["user"];
    }
    $result->free();
    }
$mysqli->close();
?>

Now I tried to use this in the index.php by including the operation.php and using it like

<div><?php echo $title ?></div>

Everything works, but I want to loop this div and get one <div> for every 'title' row in the database.

How is this possible?

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dp411805872 2014-10-17 13:09
    关注

    Well, you could declare an array at the top

    $rows = array();
    ...
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    ....
    
    foreach($rows as $row) {
        echo '<div>' . $row['title'] . '</div>';
    }
    

    That could be a solution.

    On the other hand, if you want to separate the logic and the view, you could take a look at MVC design patterns, or use a templating engine (like Twig for example)

    What a templating engine allows you to do is something like this (not tested ;-)

    $variables = array();
    while ($row = $result->fetch_assoc()) {
        $variables['rows'][] = $row;
    }
    $twig->render('index.html.twig', $variables);
    

    And in the separate index.html.twig you can use the templating language

    ...
    <body>
    {% for row in rows %}
        <div>{{ row.title }}</div>
    {% endfor %}
    </body>
    

    I hope this helps :)

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

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示