Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^6: Making an automatic counter adder for all webpages

by Nik (Initiate)
on Dec 23, 2007 at 11:38 UTC ( [id://658769]=note: print w/replies, xml ) Need Help??


in reply to Re^5: Making an automatic counter adder for all webpages
in thread Making an automatic counter adder for all webpages

I can't beleive it can be done in a so few lines!

I though i had to connect to the database table and check if the specific field is present at the table 'counters' but with the eval you give i dont have too....

Unfortunately i didn't understand how the eval() is working here and what the 'undef, $pagename)' is doing after the eval(). Inever used eval before!

Eval is trying to evaluate the statement closed within its parenthesis? Can you explain a bit more if its possible?

The $ stands for the name of the current webpage thst is running? is it with or witout the '.html'? Also because you ask we dont need to know how the current webpage loaded just its name.

in your second statemtn alsoin, the increament $db->do(), you say where pagename = ?, whats the value of ?

$db->do( 'CREATE TABLE counters (pagename text primary key, pagecoun +ter int default 0)' ); eval { $db->do('INSERT INTO counters (pagename, pagecounter) VALUES ($, 0) +', undef, $pagename); }; $db->do('UPDATE counters SET pagecounter = pagecounter + 1 WHERE pagen +ame = ?', undef, $pagename);
Also i forgot to tell you that i also need to print the current webpage's counter to the output after the increment so i need to store it in a variable called $pagecounter.
print table( {class=>'info'}, Tr( td( {class=>'lime'}, a( {href=>'/cgi-bin/show.pl?name=s +howlog'}, h1( {class=>'lime'}, $host )))), Tr( td( {class=>'yellow'}, $display_date)), Tr( td( {class=>'cyan'}, $pagecounter )) );

Replies are listed 'Best First'.
Re^7: Making an automatic counter adder for all webpages
by polettix (Vicar) on Dec 23, 2007 at 14:24 UTC
    There is a lot of context that I left out, let's proceed in order.
    • I'm assuming that the counters TABLE is already present in the database, so you don't need to create it every time you want to increase a counter. Creating tables is something that I usually avoid doing inside the code: I create them "offline", then assume that they're there when coding.
    • I usually put a RaiseError => 1 when connecting to the database. This means that any error (e.g. trying to insert a duplicate record which violates the primary key constraint) just dies. To prevent this in this specific case (in which the error is something that I consider "physiological"), I put an eval block around the $db->do(...) statement, which executes the code block but doesn't exit from the program. This is the Perl way to exception handling, you can read all this in eval's documentation.
    • I made a mistake and used a $ instead of ? in the UPDATE query, sorry!
    • The $db->do(...) can often be used to merge the prepare and execute phases into a single call, which can be easier to both write and read. The "extended" interface call is $rv  = $dbh->do($statement, \%attr, @bind_values); (see DBI docs), which means that I'm passing an undef attribute hash reference \%attr. So,
      $db->do('UPDATE counters SET pagecounter = pagecounter + 1 WHERE pagen +ame = ?', undef, $pagename);
      is equivalent to
      my $sth = $db->prepare( 'UPDATE counters SET pagecounter = pagecounter + 1 WHERE pagename = + ?'); $sth->execute($pagename);
    • Regarding the pagename value, what I'm saying is that you can use the full name instead of chopping ".html" out. As long as different pages have different names, and the same page has the same name, you can use whatever you like to name them inside the table.
    • After the two lines of code to increase the counter, you can grab the counter directly from the database, with a simple query:
      my ($counter) = $db->selectrow_array('SELECT pagecounter FROM counters + WHERE pagename = ?', undef, $pagename);
      As you can see, there's a lot to read in the DBI documentation ;)
    Summing it up:
    sub increase_pagecount_for { my ($db, $pagename) = @_; eval { # Just ignore errors if the record already exists $db->do('INSERT INTO counters (pagename, pagecounter) VALUES (?, + 0)', undef, $pagename); }; $db->do( 'UPDATE counters SET pagecounter = pagecounter + 1 ' . ' WHERE pagename = ?', undef, $pagename ); my ($counter) = $db->selectrow_array( 'SELECT pagecounter FROM counters WHERE pagename = ?', undef, $pagename ); return $counter; } ## end sub increase_pagecount_for

    Hey! Up to Dec 16, 2007 I was named frodo72, take note of the change! Flavio
    perl -ple'$_=reverse' <<<ti.xittelop@oivalf

    Io ho capito... ma tu che hai detto?
      Thank you very much for the detailed explaining, a more simple, less code needed and straightforward approach that the initail if(...) structure i had in mind

      I didn't knew i could pass variables as arguments to $db->do(...) like that, i was under the impression that i only was used when one had a fixed mysql statement with all arguments known (no vars)! If not i was using prepare and execute, i mean in case of unknown variables like '?' for '$pagename'. Can the 'undef' be ommited too as 'statemnt,,@bind_vars' ? The 'undef' is still a mystery to me on what it does although i read the help section.

      Another question is that i didnt understand why you uses this version of select:

      my ($counter) = $db->selectrow_array( 'SELECT pagecounter FROM counters WHERE pagename = ?', undef, $pagename );
      If i wanted to dot he same i would do something like:
      my $counter = 'SELECT pagecounter FROM counters WHERE pagename = ?' +, undef, $pagename );
      or
      my $sth = $db->prepare('SELECT pagecounter FROM counters WHERE pagenam +e = ?'); $sth->execute($pagename);
      Why the need for ($counter) and the method $db->selectrow_array ?
        There's nothing magic in the undef you have to pass to the do method. The required interface when you want to pass bind variables is the following:
        $dbh->do($statement, \%attr, @bind_values);
        The $statement is the query string. \%attr indicates a reference to a hash where you can pass additional attributes (much like the ones you pass to the connect method). Then, you can put a list of values to bind to the various '?' you put into $statement (yes, @bind_values is an array, but it's been put only to indicate that more values are expected here).

        If you don't want to pass additional attributes, you simply put an undef where \%attr is expected. So you end up with something like:

        $dbh->do($statement, undef, @bind_values);
        It's really nothing more than this.

        Regarding the matter of grabbing the counter value, this is plain wrong, both syntactically (you close a paren that you never open) and semantically (assigning that list to the $counter variable isn't going to help you get the counter from the DB, is it?):

        my $counter = 'SELECT pagecounter FROM counters WHERE pagename = ?' +, undef, $pagename );
        On the other hand, this is incomplete:
        my $sth = $db->prepare('SELECT pagecounter FROM counters WHERE pagenam +e = ?'); $sth->execute($pagename);
        because you still need to get the result and put it inside some variable (e.g. with fetch_whatever). My solution merges it all into a single call, and gives you the counter's value directly inside the $counter variable:
        my ($counter) = $db->selectrow_array( 'SELECT pagecounter FROM counters WHERE pagename = ?', undef, $pagename);
        The selectrow_array functions gives you the first row of the result as an array, and we know that at most one record will be given for this query. Moreover, we already know that this array is going to contain one item only (because I'm SELECTing only the pagecounter field), so assigning this array to the list ($counter) simply puts the desired page counter into the $counter variable.

        Hey! Up to Dec 16, 2007 I was named frodo72, take note of the change! Flavio
        perl -ple'$_=reverse' <<<ti.xittelop@oivalf

        Io ho capito... ma tu che hai detto?
        A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://658769]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (9)
As of 2024-07-16 10:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.