我有这个PHP代码,可以从mySQL数据库中选择最多5个数据
<?php
$servername = "localhost";
$username = "kjikk";
$password = "kjkkk";
$dbname = "ujkhjkjl";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT content_url, id FROM posts LIMIT 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<img src='http://cdn.bithumor.co/uploads/" . $row["content_url"]. "' width='50%' height='25%'> - Name: " . $row["firstname"]. " " . $row["lastname"]. " ";
}
} else {
echo "0 results";
}
$conn->close();
?>
当5个帖子被回显时,最终会垂直向上而不是彼此相邻并且在两个图像彼此相邻之后断开(br标签)
这就是它的样子:http://s9.postimg.org/vao63thr3/Screen_Shot_2015_05_25_at_11_16_03_AM.png
我希望两个图像在它们分成下两个图像之前同时彼此相邻。
我该怎么做?
答案 0 :(得分:0)
您可以创建一个div容器,对于每个带有名称的图像,您可以使用float:left;
将它们包装到父级的50%宽度的div中HTML结构:
<div class="container">
<div class="half"><img src="..."> Name</div>
<div class="half"><img src="..."> Name</div>
</div>
PHP:
if ($result->num_rows > 0) {
// output data of each row
<div class="parent">
while($row = $result->fetch_assoc()) {
echo "<div class='half'><img src='http://cdn.bithumor.co/uploads/" . $row["content_url"]. "'> - Name: " . $row["firstname"]. " " . $row["lastname"]. "</div>";
}
echo "</div>";
}
else {
echo "0 results";
}
CSS:
.parent {
width: 1000px; //your desired width
}
.parent .half {
float: left;
width: 50%;
}
这样你就可以确保每行2张图像。
提醒:正如jeroen所说,在做逻辑之前,首先尝试使用它的HTML和CSS来完成页面所具有的结构。之后,创建逻辑并将所需的结构放入其中。
答案 1 :(得分:0)
添加float:left;
while($row = $result->fetch_assoc()) {
echo "<div style='float:left;margin-right:5px;'><img src='http://cdn.bithumor.co/uploads/" . $row["content_url"]. "'> - Name: " . $row["firstname"]. " " . $row["lastname"]. "</div>";
}