lets assume we have this table called visits and it has two fields id for the page id and ip for the user’s ip address.
I have written this code and I’m wondering if it’s the best way?
$ip=$_SERVER['REMOTE_ADDR'];
$id=$_GET['id'];
$query = "SELECT
(SELECT COUNT(ip) FROM visits WHERE id = '{$id}' AND WHERE ip ='{$ip}') as visited,
(SELECT COUNT(ip) FROM visits WHERE id = '{$id}') as pageHits";
$result=mysql_query($query, $connection);
$row=mysql_fetch_array($result);
$pageHits=$row['pageHits'];
$visited=$row['visited']; //it's either 0 or 1;
if($visited==0){
$query ="INSERT INTO visits (ip , id) VALUES ('{$ip}', {$id})"
$result=mysql_query($query, $connection);
$pageHits++;
}
echo $pageHits;
I would not even check for an existing entry in the database.
Add a
UNIQUEKey onipandid(combined) and just run anINSERT IGNORE: