bogglemaster89 has asked for the wisdom of the Perl Monks concerning the following question:

Hello masters of knowledge, I have another (probably goofy) question..... I have the following code-
#!C:\strawberry\perl\bin\perl.exe use DBI; use Tie::File; $dbh = DBI->connect('dbi:mysql:Database','username','password') or die "Connection Error: $DBI::errstr\n"; $sql = "select cost, data from table"; $sth = $dbh->prepare($sql); $sth->execute or die "SQL Error: $DBI::errstr\n"; $sitedata="/xampp/cgi-bin/Smartware_LTD_Website/aberKarateCosts.html"; open(DAT,">>$sitedata") || die("Cannot Open File"); print DAT"<div id='costtable'>"; print DAT"<table border='1'>"; print DAT"<tr><th>$sth->{NAME}->[0]</th><th>$sth->{NAME}->[1]</th></tr +>"; while (@row = $sth->fetchrow_array) { print DAT"<tr><td>$row[0]</td><td>$row[1]</td></tr>"; } print DAT"</div>"; close FILE;
The above code opens a file and then writes the table result in html into that file. The file is a html file; therefore solving a previous question which i posted on here about mixing perl with html (for my needs anyway)! The problem I am having is that I only want this table to occur once, but when I run the perl more than once the table appears twice, three times etc. I have tried multiple lines to try and fix this. I want the table to up-date however when new data is added to the database, but each time an up-date occurs the original html table should be removed. please help, I think its just a line or two of code, i just cant crack the egg! Bogglemaster89
  • Comment on Perl to add a table once and then when run again delete the original table (but not the whole html document)!
  • Download Code

Replies are listed 'Best First'.
Re: Perl to add a table once and then when run again delete the original table (but not the whole html document)!
by marto (Cardinal) on Mar 08, 2010 at 15:42 UTC

    From your description I guess you need to update this table each time someone requests the page. I'd suggest using something like HTML::Template using a template loop and and the vaules from your SQL query. Rather than duplicate/repeate advice, see HTML::Template Tutorial for a well documented working exaple using CGI, DBI and HTML::Template.

Re: Perl to add a table once and then when run again delete the original table (but not the whole html document)!
by cdarke (Prior) on Mar 08, 2010 at 16:02 UTC
    You are opening the file for append in:
    open(DAT,">>$sitedata") || die("Cannot Open File");
    Try openning it for write, which will erase the previous data:
    open(DAT,'>', $sitedata) || die("Cannot Open $sitedata: $!");
Re: Perl to add a table once and then when run again delete the original table (but not the whole html document)!
by cdarke (Prior) on Mar 08, 2010 at 16:02 UTC
    duplicate post in error