user3103764
user3103764

Reputation: 87

hit counter with php and mysql database

I'm tring to make a simple php visit counter... i write this code

<?php

$Connect = mysql_connect('Localhost','root','');
$Database = mysql_select_db("myDatabaseName");
$CurrentVisit = mysql_query("SELECT visit FROM myWebsite");

$NewVisit = $CurrentVisit+1;
$UpdateField = mysql_query("UPDATE myWebsite SET visit = '$NewVisit'");
echo $NewVisit;

?>

When i execute this code the outpout is "5". Why? Where is the error? In my database i created an int(11) field call visit. i'm running this script on localhost.

Upvotes: 1

Views: 8273

Answers (3)

zavg
zavg

Reputation: 11081

You forgot to fetch result row. mysql_query function returns result resource, not row values.

You can use mysql_fetch_assoc or mysql_fetch_array function.

$Connect = mysql_connect('Localhost','root','');
$Database = mysql_select_db("myDatabaseName");
$Result = mysql_query("SELECT visit FROM myWebsite");

$CurrentVisit = mysql_fetch_assoc($Result["visit"]);

$NewVisit = $CurrentVisit+1;
$UpdateField = mysql_query("UPDATE myWebsite SET visit = '$NewVisit'");
echo $NewVisit;

If you don't need old counter value in your code (for some other manipulations) and you just need to increment database value, you can run just UPDATE myWebsite SET visit = visit+1 query as Jelle Ferwerda suggested.

P.S.: Do not use mysql_ extension cause it is deprecated. Use PDO or Mysqli instead.

Upvotes: 1

Jelle Ferwerda
Jelle Ferwerda

Reputation: 1229

After you run the query you have to run something like mysql_fetch_array. However, you can just update your counter in the database by running

UPDATE myWebsite SET visit = visit+1

assuming you do not need to show the number. This would save you a query.

More logical imhop would be to just use google analytics?

Upvotes: 0

Awlad Liton
Awlad Liton

Reputation: 9351

You missed to fetch result from result set.first fetch data like this:

$CurrentVisit = mysql_fetch_array($Result['visit']);

Upvotes: 0

Related Questions