I have articles and each of them has views. And in sidebar i display the most visited articles. All is working, but with order is problem. For example i have 4 articles. 1 article has 10 views, 2 - 7 views, 3 - 6 views, 4 - 3 views. And order is
1) 1 article - 10
2) 2 article - 7
3) 3 article - 6
4) 4 article - 3
So we can see that all is ok. But when i add one more artilce and it has 1 views order change and 5th artilce goes to top but why. It has lower views then another articles? And when 5th article get 10 views, all is ok and order restored. But why just when order resores when last artilce has more then 10 views?
<?php
$dbname="php";
$dbhost="localhost";
$dbusername="root";
$dbuserpassword="";
$optins= array(PDO::MYSQL_ATTR_INIT_COMMAND=>'set NAMES utf8');
try{
$db= new PDO("mysql:host={$dbhost};dbname={$dbname};chartset=utf8",
$dbusername,$dbuserpassword,$optins);
} catch (PDOException $ex) {
die("Fail to connect".$ex->getMessage());
}
// all post
$sql = "select * from tbl_blog order by page_view desc limit 5";
$data=$db->prepare($sql);
$data->execute();
$allpost=$data->fetchAll();
// Single Post
CREATE TABLE:
CREATE TABLE tbl_blog (
id int(11) NOT NULL,
blog_title text NOT NULL,
description text NOT NULL,
content text NOT NULL,
page_view varchar(10) NOT NULL,
category text NOT NULL,
img varchar(225) NOT NULL,
sub_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE = InnoDB DEFAULT CHARSET = utf8
</div>
For me, it's seems that the alphabetic order take control of the page_view attribute.
If your page_view attribute is define as varchar, it will be ordered like a character, for exemple:
"3" "2" "12" "11" "10" "1".
Check to put the page_view attribute as integer, to have 1 2 3 10 11 12
Hope this help
The problem is the datatype of page_view
is VARCHAR(10)
, so it gets sorted as strings, not as numbers.
Change the data type to a numeric type (e.g. INTEGER
) and it'll sort correctly.