2017-02-23 90 views
0

我試圖從一個mysql數據庫中的行創建一個div,但是當我遍歷數據庫表並將返回的行應用到div時,我只返回最後一行。這裏是代碼:試圖從MySQL數據庫創建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

你試過用Firebug或類似的工具來檢查div是否存在但不顯示(CSS的原因或...)? – GeorgeGeorgitsis

回答

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

這是一個更安全的方式。你的屬性值沒有引號,如果有的話,如中有空格,那麼它們必須用雙引號或單引號引用。

而且它應該是data-link=,而不是data-link:

而且你需要關閉的div img標籤完成

echo "<div title='{$row['divtitle']}' data-link='{$row['datalink']}'><img src='{$row['imagesrc']}'/></div>"; 
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(); 
?>