【发布时间】:2017-12-22 05:57:25
【问题描述】:
我正在尝试制作一个表格来显示 MySQL 查询的结果,但我很难做到正确...
我有 PHP 代码用这个脚本显示数据库表的内容;
<?php
// Grab the data from our people table
$sql = "SELECT * FROM people ORDER BY ID";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<div class=\"picture\">";
echo "<p>";
// Note that we are building our src string using the filename from the database
echo "<img src=\"content/uploads/" . $row['filename']
. "\" alt=\"\" height=\"125\" width=\"200\" /><br />" . "<br />";
echo $row['fname'] . " " . "<br />" . "<br />";
echo "</p>";
echo "</div>";
}
?>
但是这当然没有非常难看的表格,因为它显示了彼此下方的所有内容......所以我尝试为它制作一个表格,经过大量研究后,我找到了一个应该显示的脚本内容,但我似乎无法将其实现到我自己的代码中并最终出现错误:
无法访问数据库:未选择数据库
使用此代码:
<?php
$sql="SELECT * FROM people ORDER BY ID";
$result=mysql_query($sql) or die ("Could not access DB: " . mysql_error());
$num=mysql_numrows($result);mysql_close();?>
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td>
<font face="Arial, Helvetica, sans-serif">Value1</font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif">Value2</font>
</td>
</tr>
<?php
$i=0;while ($i < $row) {$f1=mysql_fetch_assoc($result,$i,"field1");
$f2=mysql_fetch_assoc($result,$i,"field2");
$f3=mysql_fetch_assoc($result,$i,"field3");
$f4=mysql_fetch_assoc($result,$i,"field4");
$f5=mysql_fetch_assoc($result,$i,"field5");?>
<tr>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f1; ?></font>
</td>
<td>
<font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font>
</td>
</tr>
<?php
$i++;}
?>
【问题讨论】:
-
拜托,don't use
mysql_*functions,它们不再维护,而是officially deprecated。改为了解prepared statements,并使用PDO 或MySQLi。您还想Prevent SQL Injection! -
你是如何连接到你的数据库的?看来您缺少代码。
-
我有一个单独的 conn.php 连接到页面开头的数据库... 保存所有数据库登录信息并使用第一个代码。我知道我应该尝试使用 PDO 或 MySQLi,但作为一个菜鸟,我首先要学会正确使用它,当我实现它时,我会查看 mySQLi 代码,看看需要改变什么;)
-
conn.php中是否有错误检查?在您打开
<?php标签error_reporting(E_ALL); ini_set('display_errors', 1);之后立即在文件顶部添加错误报告从一开始就学习比更改更容易,因为很多事情都会有所不同。 -
请不要在 cmets 中转储代码,那样它们几乎不可读。编辑您的原始帖子以添加新内容。
标签: php mysql image html-table