Forum Moderators: coopster

Message Too Old, No Replies

Simple Hitcounter: Works on home system, not on server

         

Target

4:27 am on Apr 4, 2005 (gmt 0)

10+ Year Member



The following bit of code works "pretty well" on my home setup, but once on the server (using mysql 3.1 and php 3.X (not sure of version) it basiaclly just creates a new row for every page hit with the date the same in each, and TodayHits field sitting at 0 in all of them. The only problem I had on my home setup was that the FIRST viewing of the page cropped up an undefined variable error for the 3rd $todayhits mention.


$fbtodaysdate = DATE('Ymd');
$todayhitscount=mysql_query("SELECT TodayHits FROM fb_hitcounter WHERE Date='$fbtodaysdate'");
while($rows=mysql_fetch_array($todayhitscount))
{
if (!$todayhitscount) {
$todayhits = 0;
}
$todayhits=$rows["TodayHits"];
}
if ($todayhits > 0)
{
$todayhits == $todayhits++;
mysql_query ("UPDATE fb_hitcounter SET TodayHits='$todayhits' WHERE Date='$fbtodaysdate' LIMIT 1");
}
if ( $todayhits < 1 ) {
mysql_query ("INSERT INTO fb_hitcounter (TodayHits, Date) VALUES ('$todayhits', '$fbtodaysdate')");
}

ironik

5:00 am on Apr 4, 2005 (gmt 0)

10+ Year Member



The only problem I could see with it, possibly, is this:


while($rows=mysql_fetch_array($todayhitscount))
{
if (!$todayhitscount) {

try changing to:


$numRows = mysql_num_rows($todayhitscount);
if ($numRows >= 1)
{
// Only need first row from the query, since you know the database should only return one result.
$row = mysql_fetch_array($todayhitscount);
$todayhits = $row['TodayHits'];
} else {
$todayhits = 0;
}

Target

5:27 am on Apr 4, 2005 (gmt 0)

10+ Year Member



Wow. Ok that fixed me right up. Don't even get the error anymore on the duplicate home site. Now if I could figure out why I'd be happier. But I can live with just knowing it work now. :)

ironik

5:36 am on Apr 4, 2005 (gmt 0)

10+ Year Member



The problem was, I think, that your code attempted to enter a loop where if there was no data returned from the query, it wouldn't execute the rest of your code.

Best to test whether you have data first, and then act on it. The mysql_num_rows() function returns the number of rows affected by a query, so in your case if it has one row or higher, the code will execute and use mysql_fetch_array() to fetch the first row in the query (if you use it consecutively, or in a loop, it will continue until it returns each row).

It'll probably be a little easier to read in future if you limit the query to 1 result, that way it there are ever 2 rows with the same date you'll only ever return 1.