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

标签 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"]}

目前这些是我正在使用的文件:

数据库.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 表格中正确显示信息?

最佳答案

如果您的文件中有 php 代码,为了执行 - 文件扩展名必须是“.php”,即:location.php 而不是 location.html

关于php - 使用 PHP 连接到数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36322965/

相关文章:

sql - 简单的 SELECT/WHERE 查询速度慢。我应该索引一个 BIT 字段吗?

php - 用 php 执行 awk linux 命令

PHP的静态成员和实例成员好像没什么区别。为什么 PHP 这样做(没有警告)?

jquery - 使用伪类选择第一个 CSS 元素

iphone - 将 HTML 复制到 UIPasteboard

html - 用覆盖整个背景的图像写在容器内

php - 调用未定义的方法 Slim\Http\Request::withStatus()

PHP localtime() 在 Apache 执行时不正确

MySQL yearweek() vs week() 返回不同的结果

mysql - 使用 n :m-relation 复制数据集