dongshi9526 2017-12-20 18:59
浏览 43
已采纳

如果将行添加到数据库,则添加HTML <div>

I am trying to make a webpage that will add a card filled with data from a database if there is a row of data there. I have a <div class> that formats the card. Is there a way to programmatically add the <div class> so each <div class> is a row of data?

This is the PHP I have, it does read all the rows properly:

//SQL SELECT statement
$result = $conn->prepare("SELECT userid, pName, pDesc, dDate FROM test");
$result->execute();
// assign returned array elements to variables
for($i=0; $row=$result->fetch(); $i++){
   $pName = $row['pName'];
   $pDesc = $row['pDesc'];
   $dDate = $row['dDate'];
}

Here is the HTML, it currently only displays the last row of data:

<h1>Project Dashboard</h1>
<div class="project-container">
  <label>Project Owner:</label>
  <span><?php echo $pName; ?></span><br>
  <label>Project Description:</label>
  <span><?php echo $pDesc; ?> </span><br>
  <label>Project Due Date:</label>
  <span><?php echo $dDate; ?> </span><br>
  <div class="progress-bar">
    <div id="myBar" class="container purple" style="height:24px;width:25%">
    </div>
  </div>
</div>
  • 写回答

1条回答 默认 最新

  • dourong6054 2017-12-20 19:42
    关注

    As mentioned in the comments, the PHP values are overwritten upon each iteration of the for loop, so only the last row of values will be displayed. For example, $pName can only hold one value at a time. So after the loop, $pName is defined as the last row's pName value.

    I suggest using a while loop to output your HTML rows. Below, I'm assuming each .project-container is a row. I'm also using PDO.

    <?php
    
    while ($row=$result->fetch(PDO::FETCH_ASSOC)) {
    
      ?><div class="project-container">
        <label>Project Owner:</label>
        <span><?=$row['pName']?></span><br>
        <label>Project Description:</label>
        <span><?=$row['pDesc']?></span><br>
        <label>Project Due Date:</label>
        <span><?=$row['dDate']?></span>
      </div><?php
    
    }
    

    Alternatively, you could fetch all the rows into a single PHP array and then loop through the array.

    $rows=$result->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($rows as $row) {
      // output row's HTML, just like above
    }
    

    See PDO::fetchAll vs. PDO::fetch in a loop for performance considerations.

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

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果