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

时间:2014-10-01 17:09:20

标签: php html css mysqli

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

现在我得到了结果,但只有一个在另一个下面。我正在做笛卡尔地图,并且必须将每个BOX放在适当的位置。 我想避免使用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 -->

1 个答案:

答案 0 :(得分:1)

否你在哪里实际将坐标分配给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,以及在每个循环中生成的坐标。