Jump to content

Why doesn't my hit counter code work?


adambedford

Recommended Posts

I've written some code that counts the number of page visits and records them in a table. The code also checks (at least it should do!)to see whether that website already has a record in the table and if not, it creates one and then records the page visit.

 

Does anyone know why the code doesn't work? I'm relatively new to PHP/MySQL and I can't come up with a reason why the code doesn't work. I don't receive an error message, but the table doesn't update.

 


//Get the website address from the URL string
$URL = $_GET[url]; 

if(mysql_num_rows(mysql_query("SELECT URL FROM hits WHERE URL = $URL"))>=1){
// Code inside if block if URL is already there

mysql_query("UPDATE hits SET counter=counter+1 WHERE $URL = URL");
}
// Else Insert new record
else {
mysql_query("INSERT INTO hits VALUES ($URL, , )");
mysql_query("UPDATE hits SET counter=counter+1 WHERE $URL = URL");
}


 

Thank in advance.

Link to comment
https://forums.phpfreaks.com/topic/190980-why-doesnt-my-hit-counter-code-work/
Share on other sites

well for one you don't receive an error because you're not outputting any mysql error.

 

for debugging you should use

mysql_query($sql) or die(mysql_error());

 

also your insert query is wrong.

mysql_query("INSERT INTO hits VALUES ($URL, , )");

 

change that to

mysql_query("INSERT INTO hits (URL, counter) VALUES ('$URL',1)");

 

you dont need that extra update after your insert. i'm not sure what the third field in your table is but if you don't want to insert anything into it you don't have to put it in your query.

 

 

This might not be what you want, but I made a little counter that is pretty simple if you want to check it out go to http://www.kinggoddard.com/portfolio.php and look at the image counter and text counter.  You could easily modify it to do more.

I think the reason is that you need to add single quotes around the $URL variable in the SQL statements since its a string.

 

try this:

//Get the website address from the URL string
$URL = $_GET[url]; 

if(mysql_num_rows(mysql_query("SELECT URL FROM hits WHERE URL = '$URL'"))>=1){
// Code inside if block if URL is already there

mysql_query("UPDATE hits SET counter=counter+1 WHERE URL = '$URL'");
}
// Else Insert new record
else {
mysql_query("INSERT INTO hits VALUES ($URL, , )");
mysql_query("UPDATE hits SET counter=counter+1 WHERE URL = '$URL'");
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.