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
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.

 

 

Link to comment
Share on other sites

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'");
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.