1

How do I update the row $pageviews by +1 each time someone visits my page. The table name is news and the row to be updated is $pageviews whose default value is +1. Should I use the update function? And how do I implement it? Below is my code. Can you show a demonstration using these data?

$data = mysql_query("SELECT * FROM news") or die(mysql_error()); 
while($info = mysql_fetch_array( $data )) 
{  
    $id = $info['id'];
    $pageviews = $info['pageviews'];
}
6
  • 6
    Have you tried something like UPDATE news SET pageviews = pageviews + 1 ?? Commented Mar 20, 2014 at 9:25
  • 3
    Oligatory "mysql is deprecated, use mysqli_* functions" comment. php.net/manual/en/book.mysqli.php Commented Mar 20, 2014 at 9:25
  • 2
    Just pass the query I gave it on your mysql_query() function.. Note : You are using an obsolete database API. Commented Mar 20, 2014 at 9:31
  • 1
    I'm now changing my functions to mysqli_* function. Thank you. Commented Mar 20, 2014 at 9:33
  • 1
    @ShankarDamodaran - That should really be an answer :) Commented Mar 20, 2014 at 9:36

2 Answers 2

1

All you want to do is to increment pageviews value each time that page renders. All you need for that:

1) Get the current value

2) Run UPDATE query updating current value + 1

To do so, you can write a function that would look like as,

function inc_page_views($id) {

  $res = mysql_query(sprintf("SELECT * FROM `news` WHERE `id` ='%s'", mysql_real_escape_string($id))); 

  $data = mysql_fetch_array($res);

  // Target view count
  $target = $data['pageviews'];

  $query = sprintf("UPDATE `news` SET `pageviews` = '%s' WHERE `id` ='%s'", $target + 1, $id);

  return mysql_unbuffered_query($query);
}

And then, when rendering a page, you can simply call inc_page_views(..here page id..) and it will do the rest

Sign up to request clarification or add additional context in comments.

Comments

0

use this query

mysql_query("Update news SET pageviews = pageviews + 1 ");

or

store the current page id in $current_page_id.

 mysql_query("Update news SET pageviews = pageviews + 1  where id = '$current_page_id' ");

2 Comments

Could you please clarify how I can store the current page id in $current_page_id ?
your news table will have unique id, which you will send in url. After that, url will be like example.com/news.php?id=33. So in this case, id is 33. So in the new.php, you must write the code like. $current_page_id = $_GET['id']; then you have to use the above 2nd query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.