使用砌体和PHP的照片网格,以从数据库中检索照片

时间:2018-08-10 05:16:46

标签: php masonry

我是编码的新手,我想使用Masonry来使我的图片像pinterest主页一样排列,但我似乎不太了解Masonry代码的工作原理。

这是我的照片和代码。

1

我能够从数据库中检索所有图像,但是所有图片都停留在屏幕左侧。我希望页面看起来像这样 2

<?php
// Create database connection
$db = mysqli_connect("localhost", "root", "", "drawingguide");


$sql = "SELECT * FROM images";
$result = mysqli_query($db, "SELECT * FROM images");

?>

<html>
<head>
<style>
.grid-item { width: 200px; }
.grid-item--width2 { width: 400px; }
</style>
    <script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.js"></script>
</head>
<?php
    while($row = mysqli_fetch_array($result)) {
echo "<div id='container'>";
echo "<img class='item' src='images/{$row['image']} ' />";
echo "</div>";
    }

mysqli_close($db);
?> 

 </html>

1 个答案:

答案 0 :(得分:1)

根据此网址https://masonry.desandro.com/,首先您必须先创建正确的HTML结构,然后是CSS和jQuery。

    <?php
    // Create database connection
    $db = mysqli_connect("localhost", "root", "", "drawingguide");


    $sql = "SELECT * FROM images";
    $result = mysqli_query($db, "SELECT * FROM images");

    ?>

    <html>
    <head>
    <style>
    .grid-item { width: 200px; }
    .grid-item--width2 { width: 400px; }
    </style>
      <script
      src="https://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous"></script>
        <script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.js"></script>
    </head>
    <div class='grid'>
<?php
    while($row = mysqli_fetch_array($result)) {
      echo "<div class='grid-item' style='background-image:url(".$row['image'].");background-size:cover'></div>";
    }

mysqli_close($db);
?>
    </div>
      <script type="text/javascript">
      jQuery(document).ready(function(){
          $('.grid').masonry({
            // options
            itemSelector: '.grid-item',
            columnWidth: 200
          });
      });
      </script>
     </html>