在网站上显示SQL表数据


Display SQL table data on website

所以我以为我把它记下来了,它一定让我知道我又搞砸了。

<?php
        $username="root";
        $password="**********";
        $database="website";
        $server="localhost";
        $connect=mysql_connect($server,$username,$password);
        ;
        @mysql_select_db($database) or die( "Unable to select database");
        mysql_select_db($database, $connect) or die ("Error selecting specified database on this server: ".mysql_error());
        $cdquery="SELECT content FROM homepage";
        $cdresult=mysql_query($cdquery) or die ("Query to get data from the first table failed: ".mysql_error());
        echo "<p>$cdresult</p>";
        mysql_close();
        ?>

是我目前的代码,用于显示我的表网站和列数据中的信息。我不确定资源id#4是什么,但它显示的是它自己,而不是内容。有人知道我做错了什么,以至于它没有显示我在内容中的信息吗?

您需要通过mysql_fetch_assoc()从结果资源中获取结果。查询成功后,返回一个结果资源,数据库连接使用该资源将结果假脱机返回。在提取行之前,它本身不包含行数据:

$cdresult = mysql_query($cdquery) or die ("Query to get data from the first table failed: ".mysql_error());
while ($row = mysql_fetch_array($cdresult)) {
  // The column is an array key in $row
  // Wrapped in htmlspecialchars() to escape for HTML output
  echo "<p>" . htmlspecialchars($row['cdresult']) . "</p>";
}

旧的mysql_*()函数已经开始了弃用过程,并且最终将从PHP中删除。建议您花一些时间学习一种更现代的API,支持准备好的语句,如MySQLi或PDO,而不是花太多时间学习mysql_*()函数。

更多提示:

您有两个呼叫mysql_select_db()。你只需要其中一个。避免使用@错误抑制运算符,因为它隐藏了在开发代码时需要看到的错误信息。

// Don't do this. Just do the next one
// @mysql_select_db($database) or die( "Unable to select database");
mysql_select_db($database, $connect) or die ("Error selecting specified database on this server: ".mysql_error());