user3871
user3871

Reputation: 12718

PHP: Updating database "num_views" of an image with id "x"

I'd like to increment a page views ("num_views") database value when a certain image in "Paging.php" is clicked on so I can keep track of how many times that image has been viewed

Paging.php:

while ($imageCounter < $imagesPerPage && ($row = $catResult->fetch_assoc())) {
    echo    "<br />ID: " . $row['imgid'] . 
            '<br /><a href="./templates/viewcomic.php?views='. $row['num_views'].'&id=' . $row['imgid'] . '&image=' . $imgpath.$row['imgname'] . '"><img src="' . $thumbpath.$row['imgthumb'] . '"/></a>' . 
            "<br />CATFK: " . $row['catfk'] . 
            "<br/>";

    $imageCounter++;
}

ViewComic.php

<?php
include 'include/header.php';

$imgid = $_GET['id']; 
$views = $_GET['views'];

include '../scripts/dbconnect.php'; 
$mysqli->query("UPDATE child_images SET num_views = ($views+1) WHERE imgid = $imgid");
mysqli_close($mysqli);
?>

It doesn't seem to be incrementing though

Upvotes: 0

Views: 79

Answers (2)

Samuel Cook
Samuel Cook

Reputation: 16828

An easier way is to just increment the value that has been posted into the database. This way you don't have to worry about data manipulate in your query string.

$imgid= $mysqli->real_escape_string($imgid);    
$mysqli->query("UPDATE child_images SET num_views = num_views + 1 WHERE imgid = $imgid");
mysqli_close($mysqli);

Upvotes: 5

Rene Pot
Rene Pot

Reputation: 24815

Just do this:

$mysqli->query("UPDATE child_images SET num_views = (num_views+1) WHERE imgid = $imgid");

Upvotes: 2

Related Questions