2016-11-15 119 views
0

我想從我的SQL數據庫中將信息拖入html表中。當我嘗試這樣做時,我得到「0結果」,但是,我能夠連接到我的數據庫,並且SQL運行在MySQL Workbench中也完全正常。看來$結果不會大於0,我不確定爲什麼會這樣。它以前工作時,我沒有在我的SQL查詢中包含連接,但就像我說的它在MySQL工作臺罰款。將數據從SQL數據庫導入到html表中

<html> 
<head><title>Employee</title> 
</head> 
<pre> 
<body> 
    <center><strong><a href="manager.html">Main Page</a></strong></center> 
    <?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$conn = new mysqli($servername,$username,$password); 
if($conn->connect_error){ 
    die("connection failed: " . $conn->connect_error); 
} 
$sql = "SELECT first_name, last_name, email, address.address, 
address.district, address.postal_code, address.phone, country.country 
FROM staff 
JOIN address ON staff.address_id = address.address_id 
JOIN city ON address.city_id = city.city_id 
JOIN country ON city.country_id = country.country_id"; 
$result = $conn->query($sql); 

if ($result->num_rows > 0) { 

    echo"<table>"; 
    echo("<table border = \"1\">"); 
    print("<tr>"); 
    print("<th>First Name</th>"); 
    print("<th>Last Name</th>"); 
    print("<th>Email</th>"); 
    print("<th>Address</th>"); 
    print("<th>District</th>"); 
    print("<th>Postal Code</th>"); 
    print("<th>Phone</th>"); 
    print("<th>Country</th>"); 
    while($row = $result->fetch_assoc()) { 
     echo "<tr><td>" . $row["staff.last_name"]. "</td><td>" . $row["staff.first_name"]. 
     "</td><td>" . $row["staff.email"]. "</td><td>" . $row["address.address"] . "</td><td>" . 
     $row["address.district"] . "</td><td>" . $row["address.postal_code"] . "</td><td>" . 
     $row["address.phone"] . "</td><td>" . $row["country.country"] . "</td></tr>"; 
    } 
} else { 
    echo "0 results"; 
} 
echo"</table>"; 
$conn->close(); 

?> 

</body> 
</pre> 
</html> 
+1

你在哪裏定義和選擇使用哪個數據庫? –

+0

你不需要一個echo \ print每行 – 2016-11-16 00:00:39

回答

2

mysqli_connect()函數有4個參數,第四是你的數據庫的名稱

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "root"; 
$dbname = 'Something'; 

$conn = new mysqli($servername,$username,$password, $dbname); 

如有疑問,See the manual

你也應該進入的習慣在繼續之前測試數據庫訪問是否有效,錯誤消息通常非常適合幫助您調試代碼

$result = $conn->query($sql); 
if (!$result) { 
    echo $conn->error; 
    exit; 
} 
0

補充說,用於從HTML文件中嵌入表中獲取數據PHP代碼是不是一個好thing.so它的更好,如果你使用單獨的PHP文件的方式來從表中檢索數據你可以保護你的數據庫的表信息。

我用php文件檢索數據並將結果轉換爲json數據輸出在php file.that中,json輸出從'setData.js'文件中讀取,併爲html文件中的表設置數據集。

我將這個例子添加到我的github中,以便您可以參考它。 here's my github repository

相關問題