I have this code for counting number of replies in one topic,
$sql = mysql_query("SELECT count(*) FROM ".prefix."REPLY WHERE TOPIC_ID = '$t' AND R_AUTHOR = '$m' ".$Open_SQL." ") or die(mysql_error());
$Count = mysql_result($sql, 0, "count(*)");
if ($Count > 0) {
$Count = $Count;
}
else {
$Count = "";
}
return($Count);
mysql_free_result($sql);
}
it shows the results fine, what I need is to order this results in DESC.
any suggestions?
You are just selecting Count(*) which means there is nothing to sort, because you will exactly get ONE dataRow, containing the count.
What you probably want to do is to add a GROUP BY-clause and select different Stuff and order it by count:
table
user | type
1 apple
2 apple
3 cherry
With such a table, you can group by type and sort the cherry/apple count later.
SELECT count(*) AS c, type FROM table GROUP BY type ORDER by c DESC/ASC
Result:
c | type
2 apple
1 cherry
But without GROUP BY it would just return the total count: 3 - no sorting possible of course.
you probably want to do something like this
SELECT some-field, count(*) as count
FROM your-table
WHERE your-clauses
AND more-clauses
GROUP BY some-field
ORDER BY some-field desc
Related
I wanted to know if it is possible to obtain the 10 most viewed articles that week (Between today and 7 days back) using PDO PHP.
The main problem is that on two separate tables. Primary table is the table of articles. And the second table is a table visitors by IP.
Posts (ARTICLE TABLE):
1.ID (text)
2.TITLE (text)
3.TEXT (text)
Visitor (COUNTER TABLE):
1.ID (number)
2.IP (text)
3.DATE (TIMESTAMP)
4.ID_POSTS (text)
The full php code:
$week_start = date('Y-m-d',time()+( 1 - date('w'))*24*3600);
$week_end = date('Y-m-d',time()+( 7 - date('w'))*24*3600);
$query = "SELECT * FROM visitor WHERE DATE BETWEEN '".$week_start."' AND '".$week_end."' LIMIT 0, 10 ";
$result = $db->prepare($query);
$result->execute();
$i=1;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$post[$i]=$row[ID];
$i++;
}
for ($i = 1; $i <= 10; $i++) {
$query = "SELECT * FROM POSTS WHERE ID_POST = '".$post[$i]."' LIMIT 0, 10";
$result = $db->prepare($query);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo<<<PRINT
$row[ID].$row[TITLE]: $row[text]
PRINT;
}
}
The problem I think is that you have to count how many people were at the table wrote the secondary then move the primary table.
Steps:
1. Count how many entered each article each week by the secondary table
2. extract the 10 Most Viewed same week
3. present the 10 most read article in the same week by the main table
Thanks in advance.
For such a query, I would expect a COUNT(), GROUP BY, ORDER BY, and LIMIT 10. Hence:
SELECT id_post, COUNT(*) as cnt
FROM visitor v
WHERE DATE BETWEEN '".$week_start."' AND '".$week_end."'
GROUP BY id_post
ORDER BY cnt DESC
LIMIT 0, 10 ;
Note: The WHERE clause always followed the FROM clause.
Also, you should not be embedding dates in the query string. You should learn to use parameters instead.
select * from (select id, count(1) as cnt
from visitor where date > (NOW()- INTERVAL 7 DAY) group by id) v1, posts p
where v1.id = p.id
order by v1.cnt desc
limit 10
Not tested.
does anyone know how you would count the total number of times a value appears in a single column.
for instance my table looks like:
user_id | liked_id | likes
3 1 1
4 1 1
what i want to do is count the total of the likes column where liked_id matches.
So liked_id 1 has 2 likes?
can someone please show me how i might do this?
function count_likes() {
global $connection;
global $profile_id;
$query = "SELECT likes, count(*) FROM ptb_likes GROUP BY liked_id";
$count_likes_set = mysql_query($query, $connection);
confirm_query($count_likes_set);
return $count_likes_set;
}
Try this:
SELECT liked_id, SUM(likes) FROM ptb_likes GROUP BY liked_id
you should grouped them by liked_id
SELECT liked_id, count(*) totalLikes
FROM ptb_likes
GROUP BY liked_id
if you just want the number of rows with like_id of 1,
SELECT liked_id, COUNT(likes) FROM ptb_likes WHERE liked_id = 1;
If you want the the frequency of each like_id:
SELECT liked_id, COUNT(likes) FROM ptb_likes GROUP BY liked_id;
As a note: don't use SUM as that adds all the values of like_id, and if you have a like_id greater than 1, your count will be wrong. Use count instead.
Lets say I have 3 columns and 3 rows, the first column is for ID, the second is names, third is votes. like:
+----+------+-------+
| id | name | votes |
+----+------+-------+
| 1 | bob | 7 |
| 2 | jill | 2 |
| 3 | jake | 9 |
+----+------+-------+
How can I have PHP compare the values in the votes field and sort it by whichever had the highest number, and attach a rank of #1,2,3, etc. depending on how many votes it had?
Each value will be displayed on a separate page. For example, if I went to 'bob's page' with the ID of 1, I would need it to display '#2 bob' since he would be ranked 2nd by votes.
You can make a separate column rank and update it by running the following code whenever your vote changes. This method will make you more efficient as in this you wont be sorting the table again and again when user visits his page:
$q = "select * from tableName order by votes DESC";
$a = mysql_query($q);
$count = 1;
while($arr = mysql_fetch_array($a){
$up = "update tableName set(rank) VALUES($count) WHERE name=$arr['name']";
$aq = mysql_query($up);
$count++;
}
Now on individual pages, you can just retrieve the rank value and show
$user = "Bob";
$q = "select rank from tableName where name=$user";
$a = mysql_query($q);
$arr = mysql_fetch_array($a);
echo $arr[0];
Also this(a slight modification in other answer) should work for you :-
SELECT #rownum:=#rownum+1 AS rank, name, vote FROM table, (SELECT #rownum:=0) as P ORDER BY vote DESC
You could read the values returned by your query into an array and then sort said array.
You want a SELECT query doing an ORDER BY votes, and create a special variable to handle the rank of a row:
SELECT #rownum:=#rownum+1 AS rank, name, vote FROM table, (SELECT #rownum:=0) ORDER BY vote DESC
This query should let you fetch an array with the rank, name, and number of votes of each person of your table.
Alternatively, you can just sort by vote, and add the rank value yourself with PHP.
You can use the MySQL 'ORDER BY' and display those ranks using PHP:
For this example:
<?php
//connection
//DB selection
$query = "SELECT * FROM table_votes ORDER BY votes DESC";
$result = mysql_query($query);
for(int $i=1; $row = mysql_fetch_array($result);i++)
{
echo "#".$i.$row['name']."<br/>";
}
?>
Say i have a table Guest and it has column g_id : values 1 to 10.
Now i want the query to return me the g_id's neither in ascending order nor in descending..
but i want the 4th then 3rd and then 5th entry, in this particular order.
Also i want just the 4th 3rd and 5th entry.
say my entries have an id and a name . ;i.e. my table Guest has these two tables.
Now my table is as following.
1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J
Now i want just the entry with 4th 3rd and 5th g_id, and in this particular order.
How do i write the SQL query?
Thanks.
Select * from Guest ___________???
Kindly fill in the gaps.
You can use a CASE statement in your ORDER BY to use a fake column to sort on and a WHERE IN clause to only return the values you need.
SELECT *
FROM Guest
WHERE g_id IN (3, 4, 5)
ORDER BY
CASE WHEN g_id = 4 THEN 1
WHEN g_id = 3 THEN 2
WHEN g_id = 5 THEN 3
END
What is the order that deteremines whether something is 4th, 3rd or 5th? Without an ORDER BY clause, the data is returned in an indeterminate order by SQL. You cannot rely on the order that rows are entered or stored in the database table itself.
You can hard-code what you are asking like this:
select *
from Guest
order by case
when g_id = 4 then 1
when g_id = 3 then 2
when g_id = 5 then 3
else 4
end
One solution is the case statement:
select g_id from (
select g_id, case g_id
when 4 then 1
when 3 then 2
when 5 then 3
else 0
end virtcol
where virtcol != 0
order by virtcol
);
I'm not sure how set your ordering will be, but you can order by specifics:
ORDER BY
g_id = 4 DESC,
g_id = 3 DESC,
g_id = 5 DESC
You may be better off selecting the entries as they are and doing something like this in your php code:
$order = array('4 ', '3 ', '5 ');
$data = array();
while ($row = $result->fetch()) {
$data["$row->g_id "] = $row;
}
$data = array_merge(array_flip($order), $data);
I think that the answer mostly depends on the DBMS you are working on.
In Oracle the query below, even though inefficient, should work
select * from
(select * , rownum as order from guest order by id asc ) b
where b.order = 4
UNION
select * from
(select * , rownum as order from guest order by id asc ) b
where b.order = 3
UNION
select * from
(select * , rownum as order from guest order by id asc ) b
where b.order = 5
Not sure if something of more efficient is possible with a simple query,
i would use the monster above only and only if the table you are querying is very small.
You also have another option if the table is big and you have to extract only the first rows. In the case you described, I would retrieve the first 5 rows and then programmatically I would extract the rows in position 4,3,5.
you can extract the first 5 rows with this query in oracle
select * from guest order by id asc where rownum < 6
This query will get you the 3rd, 5th, and 4th items (limit 2, 1 means "retrieve starting with 3rd item, with total number retrieved = 1 records)
(select g_id from Guest limit 2,1)
UNION (select g_id from Guest limit 4,1
UNION (select g_id from Guest limit 3,1)
I have a database that looks something like this:
user_id photo_id
1 1
1 2
1 3
1 4
2 5
2 6
I want to get a list of the most popular users from it. Like this:
Popular Users: 1 (4) & 2 (2)
How would I go about doing that in mysql in PHP?
Thanks, Coulton
PS: I do know much about mysql commands so you don't have to dumb it down. Thanks!
The basic query would be:
select user_id, count(user_id) as cnt
from yourtable
group by user_id
order by cnt desc
To display the results, something like:
$results = array()
while($row = mysql_fetch_assoc($query_result)) {
$results[] = "{$row['user_id']} ({$row['cnt']})"
// repeat for however many results you want
}
echo "Popular user: ", implode(" & ", $results);
select user_id, count(user_id) as count from table order by count desc group by user_id
something like that anyway...
This can be accomplished using only SQL commands. Here's what I'd do:
SELECT user_id, count(user_id) uid_count
FROM <<table>>
GROUP BY user_id
ORDER BY uid_count DESC
LIMIT 5;
GROUP BY collects rows that all have the same user_id, and ORDER BY ... DESC sorts the results in descending order, so the first rows represent the most popular users. LIMIT gives you the top 5 results.
The database query will look something like this:
select user_id, count(photo_id) as c
from table group by user_id
order by c desc limit 5;
In PHP, it would look something like this:
$sql = 'select user_id, count(photo_id) as c from table group by user_id order by c desc limit 5';
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['user_id'];
echo $row['c'];
}
SELECT COUNT(a.category_id) as cnt,b.category,b.image FROM bookings as a
INNER JOIN service_category as b ON a.category_id=b.category_id
GROUP BY a.category_id ORDER BY cnt DESC LIMIT 6