Most viewed news item

Hello guys,

I have a simple script which counts how many pageviews my newsitems have:

[php]// Page ID
$page = $row[id];

$result = mysql_query(“SELECT page_count FROM view WHERE page_id = $page”);
$t_count = mysql_num_rows($result);

if($t_count > 0){
$cnt = mysql_result($result, 0, ‘page_count’);
mysql_query(“UPDATE view SET page_count = $cnt WHERE page_id = $page”);
mysql_query(“INSERT INTO view ( page_id , page_count ) VALUES ($page, ‘1’)”);
$cnt = 1;

// echo the number of hits
echo “Pageviews: $cnt”;[/php]

When I go to phpmyadmin, I can just click on “page_count” to sort my newsitems, most viewed newsitem on top.

But does anyone know how I can do the same thing in PHP, so I can add the 10 most viewed newsitems on my website.

Thank you for your help.

SELECT `page_id`, `page_count` FROM `view` ORDER BY `page_count` DESC LIMIT 10;

Thank you M@tt, this is how I got it to work:

[php] $sql = “SELECT page_id,page_count FROM view ORDER BY page_count DESC LIMIT 0, 10”;
$res = mysql_query($sql);

if (mysql_num_rows($res)) 
    $i = 1; 
    while($row = mysql_fetch_array($res)) 
        $row[datum] = substr($row[datum], 0, 5); 
        if ($i == 50) 
            echo "$row[page_count]<br>"; 
            echo "$row[page_count]<br>"; 
    echo "<i>No News Items</i>"; 
} [/php]

My next problem is that this sorts the most viewed news item of all time…
Do you perhaps know how I can only sort the most viewed news items of today or this week?

The other problem is that the news items are in another table “newsdb” instead of “view”.

Does anyone know how to solve this problem I mentioned in my last post, how to just select the most viewed news items of this week instead of all time? Thanks!

It’s hard to say without seeing your full table structure. You would need a column that specifies a date/timestamp.

Sponsor our Newsletter | Privacy Policy | Terms of Service