如何在PHP中使用while循环创建DIV框


How can I create DIV boxes with a while loop in PHP?

我正试图通过从MySQL读取其X,Y坐标来创建一个div框。我在同一个文件上使用PHP和HTML。我也包含了我的CSS(之后我会制作一个单独的CSS文件)。

现在我正在得到结果,但只把一个框放在另一个框下面。我正在做一张笛卡尔地图,必须把每个盒子放在合适的位置我想避免使用Javascript和Canvas,只使用纯css、html和php我之所以使用DIV,是因为有一个特定的原因,要在它们之后添加信息。下面是我的代码,提前感谢您的帮助!

我拥有的文件顶部:

<!DOCTYPE html>
<?php
include 'db_conn.php';
//query to get X,Y coordinates from DB
$coord_sql = "SELECT x_coord, y_coord FROM coordinates";
$coord_result = mysqli_query($conn,$coord_sql);
//see if query is good
if($coord_result === false) {
    die(mysqli_error()); 
}
?>

我的CSS在头部:

<style type="text/css">
    #desk_box{ width: 20px; height: 30px; border:10px solid black; margin: 10px;}   
</style>

我试图在这里循环,对于存在的每一行,在其适当的位置创建一个div:

<div class="section_a" >
  <p>Section A</p>
  <?php
//get number of rows for X,Y coords in the table
while($row = mysqli_fetch_assoc($coord_result)){    
  //naming X,Y values
    $x_pos = $row['x_coord'];
          $y_pos = $row['y_coord'];     
    //draw a box with a DIV at its X,Y coord    
    echo "<div id='desk_box'>box here</div>";                                           
    } //end while coord_result loop
?>
</div> <!-- end div section_a -->

没有,您实际将坐标分配给div.的位置

像这样:

//get number of rows for X,Y coords in the table
while($row = mysqli_fetch_assoc($coord_result)){    
    //naming X,Y values
    $x_pos = $row['x_coord'];
    $y_pos = $row['y_coord'];     
    //draw a box with a DIV at its X,Y coord    
    echo "<div id='desk_box' style='position: absolute;
                                        left: " . $x_pos . "px;
                                         top: " . $y_pos . "px;'>
           box here</div>";                                           
} //end while coord_result loop

该代码获取每个X/Y坐标,并从父DIV的左/上角绝对定位DIV,在每个循环中生成坐标。