我想显示一个像Pinterest一样的文字网格。 我的网站是一个新闻提要网站,用户可以上传文本。
显示和获取数据库文本的代码是:
<?php
//connect
mysql_connect("host","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
//query the database
$getnews = mysql_query("SELECT * FROM news ORDER BY id DESC") or die(mysql_query());
while ($row = mysql_fetch_assoc($getnews))
{
//get data
$id = $row['id'];
$title = $row['title'];
$body = $row['body'];
$date = $row['date'];
echo "
<b>$title posted on $date</b><br>
";
echo nl2br($body);
echo "<hr>
";
}
?>
发布文本的代码如下:
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('host', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if ($_POST['post'])
{
//get data
$title = $_POST['title'];
$body = $_POST['body'];
//check for existance
if ($title&&$body)
{
mysql_connect("host","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','$title','$body','$date')") or die(mysql_error());
die("Your text has been posted!");
}
else
echo "Please fill out your name and text<p>";
}
?>
答案 0 :(得分:5)
只需将结果写为简单的<ul><li>
元素,然后使用CSS设置样式。不要用PHP来创建布局。
之后,您可以使用jQuery Masonry插件创建类似Pinterest的布局。
您的“结果显示”代码如下:
echo '<div id="grid">';
while ($row = mysql_fetch_assoc($getnews))
{
//get data
echo '<div class="item">';
$id = $row['id'];
$title = $row['title'];
$body = $row['body'];
$date = $row['date'];
echo "<b>$title posted on $date</b>";
echo nl2br($body);
echo "</div>";
}
echo "</div>";
在更改之后,您的最终HTML将如下所示:
<div id="grid">
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
...
</div>
从给定地址下载jQuery Masonry并将其包含在您的页面中,如下所示:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="/path/to/jquery.masonry.min.js"></script>
所有项目的大小由CSS处理。物品应该浮动。
.item {
width: 220px;
margin: 10px;
float: left;
}
最后,在页面加载后调用Masonry:
$(function(){
$('#grid').masonry({
// options
itemSelector : '.item',
columnWidth : 240
});
})