I don't see you doing any text output, so I can't see where your texts come from, and apart from that, your html code is seriously screwed up and should not be expected to look in any particular way at all.
echo "<tr><td>";
while($row=mysql_fetch_array($result)){
echo "</tr>";
echo " <a href=\"$row[element_2]\"><img src=\"images/$row[element_5]\" border=\"1\" width='$maxwidth' alt=\"$row[element_1]\" title=\"$row[element_1]\"></a></tr>";
}
The above will produce the following html
<tr><td>
</tr><a><img/></a></tr>
</tr><a><img/></a></tr>
</tr><a><img/></a></tr>
... goes on like this for as many pictures as you have
And it should be
<table>
<tbody>
<tr>
<td><a><img/></a></td>
<td><a><img/></a></td>
<td><a><img/></a></td>
</tr>
<tr>
<td><a><img/></a></td>
<td><a><img/></a></td>
<td><a><img/></a></td>
</tr>
</tbody>
</table>