简体   繁体   中英

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

I am trying to create a DIV box by reading its X,Y coordinates from MySQL. I am using PHP and HTML on the same file. I have included my CSS as well (I will make a separate CSS file afterwards).

Right now I am getting results but only boxes one under the other. I am doing a cartesian map and have to place each BOX on their appropriate position. I want to avoid using Javascript and Canvas, just pure css,html and php I am using DIVs for a specific reason to put information in them after. Below is my code, thanks in advance for the help!

Top of the file I have:

<!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()); 
}
?>

My CSS in the head:

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

I am trying to loop through here, for each row that exists create a div at its appropriate location:

<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 -->

No where are you actually assigning the coordinates to the DIV.

Like so:

//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

This code is taking each X/Y coordinate and absolutely positioning the DIV from the left/top corner of the parent DIV, with the coordinates you generate in each loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM