简体   繁体   中英

PHP/MYSQL hits counter on dynamic page

I've been trying to code a php/mysql hit counter on a dynamic page but it just doesn't seem to work. Here's the code so far..

while{  
$incre=+1;
$update=$db->prepare("UPDATE hits=hits+1 WHERE id="$sid"");
$data=array($incre,$sid);
$update->execute($data);

$db->prepare("INSERT INTO thread (hits) VALUES (1) ON DUPLICATE KEY UPDATE hits=hit+1`");

if($count==null)
    {echo "<p style='text-align:center; clear:both; color:black; font-size:95%;'>Total visits: 0</p>";}
else
    {echo "<p style='text-align:center; clear:both; color:black; font-size:95%;'>Total visits: <b style='color:red;'>".$count."</b></p>";}
} 

So, there are a lot of problems with your code. You don't set up the sql update statement in a safe way (sql injection). Then you don't call it correctly (you should use named parameters always). Then your insert statement is never called. You also never get the hits count from the db to display. Lots of weird things going on.

$update = $db->prepare("INSERT INTO thread (id, hits) VALUES (:id, 1) ON DUPLICATE KEY UPDATE hits=hits+1");
$update->execute(array(':id' => $sid));

$query = $db->prepare("SELECT hits FROM thread WHERE id=:id");
$query->execute(array(':id' => $sid));
$counter = $query->fetchColumn(0);

echo "<p style='text-align:center; clear:both; color:black; font-size:95%;'>Total visits: <b style='color:red;'>".$counter."</b></p>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM