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

i use the following code to identify users that visit my webpage through their hostnames and cookies that i store in their pc through the browser.
%cookie = fetch CGI::Cookie if $ENV{HTTP_COOKIE}; $cookie1 = cookie( -name=>"host", -value=>$host, -expir +es=>"+7d" ); $cookie2 = cookie( -name=>"xronos", -value=>$xronos, -expir +es=>"+7d" ); $cookie3 = cookie( -name=>"visits", -value=>cookie(visits) + 1, -expir +es=>"+7d" ); print header( -charset=>'iso-8859-7', -cookie=>[$cookie1, $cookie2, $c +ookie3] ); ............................... ............................... ............................... if ( $ENV{HTTP_COOKIE} ) { $st = $db->prepare( 'SELECT * FROM logs' ); $st->execute(); while ( $row = $st->fetchrow_hashref ) { if ( cookie(host) eq $row->{host} ) { $db->do( "UPDATE logs SET visits = visits + 1" ) or die $db-> +errstr; } } } elsif ( !$ENV{HTTP_COOKIE} ) { $db->do( "INSERT INTO logs VALUES ('$host', '$xronos', 'index', 1)" + ) or die $db->errstr; }
Is there any other better way to write the above code? I want the logs database to add +1 to variable visits each time the same user visits my webpage again!
Any idea how to make the aboev code better or you see something wrong in it? Thanks
The Devil Is In The Details!

Replies are listed 'Best First'.
Re: Cookies or maybe another way to do it.....
by tachyon (Chancellor) on Jun 27, 2004 at 23:27 UTC

    I think you want something like this. Note use ? placeholders to ensure values get correctly quoted or you have a big security hole. if ( $val ) {} elsif ( ! $val ) {} is an if/else - there are no other options.

    if ( $cookie{host}->value ) { $db->do( "UPDATE logs SET visits = visits + 1 WHERE host = ?", $co +okie{host}->value ) or die $db->errstr; } else { $db->do( "INSERT INTO logs VALUES (?, ?, 'index', 1)", $host, $xron +os ) or die $db->errstr; }

    cheers

    tachyon

Re: Cookies or maybe another way to do it.....
by borisz (Canon) on Jun 27, 2004 at 22:55 UTC
    your UPDATE statement look wrong to me, it updates all visites fields in the table logs.
    if ( $ENV{HTTP_COOKIE} ) { $dbh->do(q{ UPDATE logs SET visits = visits + 1 WHERE host = ? }, {}, $host ); }
    Boris