我试图从mysql数据库中的行创建div,但是当我遍历数据库表并将返回的行应用到div时,我只返回最后一行。这是代码:
<?php
$servername = "localhost";
$username = "divs";
$password = "password";
$dbname = "setdivs";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from getinfo";
$result = $conn->query($sql);
echo " <div id=\"vertical-with-linking\" class=\"fn-container fn-vertical\" style=\"color: rgb(51, 51, 51); margin: 0px auto; overflow: hidden; position: relative; width: 580px; height: 280px\">";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["divtitle"]. " " . $row["datalink"] . "<br>";// works fine
//echo "<div title = " . $row['divtitle'] . " data-link: " . $row['datalink'] . "><img src=" . $row['imagesrc'] . " />";//returns last row only
}
} else {
echo "0 results";
}
$conn->close();
?>
非常感谢任何建议。
答案 0 :(得分:2)
这是一种更安全的方式。您没有关于属性值的引号,如果有$row['divtitle']
中有空格,那么它们必须用双引号或单引号引用。
它也应该是data-link=
而不是data-link:
你需要在img标签完成后关闭div
echo "<div title='{$row['divtitle']}' data-link='{$row['datalink']}'><img src='{$row['imagesrc']}'/></div>";
答案 1 :(得分:0)
你应该关闭div
echo "<div title = " . $row['divtitle'] . " data-link: " . $row['datalink'] . "><img src=" . $row['imagesrc'] . " />";//returns last row only
到
echo "<div title = " . $row['divtitle'] . " data-link: " . $row['datalink'] . "><img src=" . $row['imagesrc'] . " /></div>";//returns last row only
答案 2 :(得分:0)
我认为问题可能是你的Div没有关闭。
试试这个。
<?php
$servername = "localhost";
$username = "divs";
$password = "password";
$dbname = "setdivs";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from getinfo";
$result = $conn->query($sql);
echo " <div id=\"vertical-with-linking\" class=\"fn-container fn-vertical\" style=\"color: rgb(51, 51, 51); margin: 0px auto; overflow: hidden; position: relative; width: 580px; height: 280px\">";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["divtitle"]. " " . $row["datalink"] . "<br>";// works fine
echo "<div title = " . $row['divtitle'] . " data-link= " . $row['datalink'] . "><img src=" . $row['imagesrc'] . " /></div>";//returns last row only
}
echo "</div>";
} else {
echo "0 results";
}
$conn->close();
?>