|
Posted by Toby A Inkster on 05/22/07 06:36
shotokan99 wrote:
> this works fine with me, but is there much better approach compared to
> what im doing?
Yes.
<?php
require('conn.php');
$q="SELECT xid,xrank,xtitle,xartist,xref,xtaglink,ximg,xswf
FROM $dbf_vid
ORDER BY xrank;";
$res=mysql_query($q) or die('error: cannot perform query on new');
$i=0;
$shown_fields = array('id', 'rank', 'title', 'artist', 'ref');
while($data = mysql_fetch_assoc($res))
{
$class = (++$i%2==0) ? 'even' : 'odd';
printf('<tr class="%s">', htmlentities($class));
foreach ($shown_fields as $f)
printf('<td class="%s">%s</td>', $f, htmlentities($data['x'.$f]));
printf('<td class="delete"><a href="mtvdel.php?id=%s&dbf=mtv_topvid_ph">delete</a></td>',
htmlentities(urlencode($data['xid'])));
$editurl = sprintf('id=%s&rank=%s&title=%s&by=%s&taglink=%s&ref=%s&img=%s&swf=%s',
urlencode($data['xid']),
urlencode($data['xrank']),
urlencode($data['xtitle']),
urlencode($data['xartist']),
urlencode($data['xtaglink']),
urlencode($data['xref']),
urlencode($data['ximg']),
urlencode($data['xswf']));
printf('<td class="edit"><a href="%s">edit</a></td>', htmlentities($editurl));
echo "</tr>\n";
}
?>
Advantages:
* You don't specify which columns exist in your database, so you
may be fetching other columns that you don't need. Hence I've
specified the exact columns to select.
* I've removed all the colours, fonts and so on from the output,
replacing them with class="odd" and class="even" attributes on the
table cells, which can be styled appropriately via CSS.
* I've not specified any widths -- browsers are generally pretty
good at guessing widths themselves. I've added classes to the
table cells so that you can use CSS to specify widths if required.
* I've made sure that all output is properly urlencoded and special
HTML characters are escaped. A mixture of printf(), htmlentities()
and urlencode() makes this fairly easy and very clear.
* I've output the first five columns using a foreach loop, which
reduces repetition in your code.
* I've used mysql_fetch_assoc() which is significantly faster than
repeated calls to mysql_result(). This also eliminates the need
to call mysql_numrows() entirely.
* I've added a line break after "</tr>" to make the resulting HTML
slightly easier to read.
--
Toby A Inkster BSc (Hons) ARCS
http://tobyinkster.co.uk/
Geek of ~ HTML/SQL/Perl/PHP/Python/Apache/Linux
Navigation:
[Reply to this message]
|