FGOD
FGOD

Reputation: 103

How to make a table with MySQL queries

I'm trying to make a table that shows the results from a query of MySQL, but I'm having a hard time to get it right...

I had the PHP code to show the content of the database table with this script;

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

but that of course doesn't have tables which is pretty ugly as it displays everything underneath each other... so I tried to make a table for it and after a lot of research I found a script which should have displayed the content but I can't seem to implement it into my own code and ended up with the error:

Could not access DB: No database selected

Using this code:

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

Upvotes: 1

Views: 90

Answers (1)

Anigel
Anigel

Reputation: 3437

Not sure what is going on here

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

Mysql_fetch_assoc only accepts one argument

The correct way to use it is as demonstrated in the 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
}

If you had errors and warnings turned on, then you would get helpful error messages telling you what was wrong with your code. It is always recommended to turn them on for development.

Upvotes: 1

Related Questions