使用PHP连接到数据库时出错

时间:2016-03-31 02:12:59

标签: php html sql

我目前在表格中存储的信息如下:

+----+------+-------+-----------+-----------+
| 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");
}
?>

location.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 个答案:

答案 0 :(得分:2)

如果你的文件中有php代码,为了执行 - 文件扩展名必须是&#39; .php&#39;即:location.php不是location.html

答案 1 :(得分:0)

mysql_select_db接受单个参数。它是数据库名称。

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