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 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。