2016-03-31 175 views
3

我現在有存儲在一個表中的信息如下:錯誤連接到數據庫,PHP

+----+------+-------+-----------+-----------+ 
| id | name | state | xcoord | ycoord | 
+----+------+-------+-----------+-----------+ 
| 1 | lake | CA | 36.746585 | 22.234564 | 
| 2 | pond | TX | 26.123123 | 12.456789 | 
+----+------+-------+-----------+-----------+ 

我有一個顯示在我的網頁的HTML表:

<html> 
 
    <head> 
 
    <title>Locations</title> 
 
    </head> 
 
    <body> 
 
    <table border=1> 
 
     <tr> 
 
     <th>ID</th> 
 
     <th>Name</th> 
 
     <th>State</th> 
 
     <th>X Coord</th> 
 
     <th>Y Coord</th> 
 
     </tr> 
 
    </table> 
 
    </body> 
 
</html>

我想用我的數據庫中存儲的值在我的網頁上傳播表格。目前,當我嘗試這樣做編程,我得到這個結果:

"; ?> 
ID Name State X Coord Y Coord 
{$row['id'] {$row["name"] {$row["state"]} {$row["xcoord"]} {$row["ycoord"]} 

目前這些都是我使用的文件:

db.inc.php

<?php 
/* 
* db.inc.php 
* These are the DBMS credentials and the database name 
*/ 
$hostName = "xxxx"; 
$databaseName = "yyyy"; 
$username = "zzzz"; 
$password = "wwww"; 
// Show an error and stop the script 
function showerror() 
{ 
    if (mysql_error()) 
     die("Error " . mysql_errno() . " : " . mysql_error()); 
    else 
    die ("Could not connect to the DBMS"); 
} 
?> 

位置。 html

<html> 
    <head> 
     <title>Locations</title> 
    </head> 
    <body> 
     <table border=1> 
      <tr> 
       <th>ID</th> 
       <th>Name</th> 
       <th>State</th> 
       <th>X Coord</th> 
       <th>Y Coord</th> 
      </tr> 

      <?php 

include 'db.inc.php'; 

// Connect to MySQL DBMS 
if (!($connection = @ mysql_connect($hostName, $username, $password))) 
    showerror(); 

// Use the location database 
if (!mysql_select_db($databaseName, $connection)) 
    showerror(); 

// Create SQL statement 
$query = "SELECT * FROM locations"; // the table name is "locations" 

// Execute SQL statement 
if (!($result = @ mysql_query ($query, $connection))) 
    showerror(); 

// Display results *** My inclination is that something is awry with the following echo 
while ($row = @ mysql_fetch_array($result)) 
    echo "<tr> 
<td>{$row["id"]}</td> 
<td>{$row["name"]}</td> 
<td>{$row["state"]}</td> 
<td>{$row["xcoord"]}</td> 
<td>{$row["ycoord"]}</td> 
</tr>"; 
?> 

     </table> 
    </body> 
</html> 

如何正確顯示我的HTML表格中的信息?

回答

2

如果你有PHP代碼在你的文件,以執行 - 文件擴展名必須是「.PHP」,即:不location.php location.html

+0

謝謝。將它重命名爲「location.php」的確有竅門。 – Queue

0

mysql_select_db接受單一參數。它是數據庫名稱。

<?php 
    if (!mysql_select_db($databaseName)) 
    showerror(); 
?> 
+0

但是,使用上面示例代碼中顯示的兩個參數設置沒有出現問題。 – Queue