如何使用MySQL查询创建表

问题描述 投票:1回答:1

我正在尝试创建一个显示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++;}
?>
php mysql image html-table
1个回答
1
投票

不知道这里发生了什么

mysql_fetch_assoc($result,$i,"field1")

Mysql_fetch_assoc只接受一个参数

使用它的正确方法如php man page所示

while ($row = mysql_fetch_assoc($result)) 
{?>
  <tr>
    <td>
      <font face="Arial, Helvetica, sans-serif"><?php echo $row['value1']; ?></font>
    </td>
    <td>
      <font face="Arial, Helvetica, sans-serif"><?php echo $row['value2']; ?></font>
   </td>
  </tr>
<?php
}

如果您打开了错误和警告,那么您将收到有用的错误消息,告诉您代码出了什么问题。始终建议turn them on进行开发。

© www.soinside.com 2019 - 2024. All rights reserved.