how to display each article total comments - php

I have two tables which I have joined. The query looks like this:
SELECT *, AVG(rate)
FROM comments c
LEFT JOIN supps s
on c.tutorialid = s.tutid
WHERE category = 'Protein'
GROUP BY tutorialid
ORDER BY $orderby $sort LIMIT $startrow,$limit";
And I have the code below to get the total comments:
//find the number of comments
$commentNum = mysql_num_rows($result);
When I use echo $commentNum, it displays the total for all comments on every row for example if I had:
echo "".$row['title'] ."<br>";
echo $commentNum .
It would give me the total comments for all the posts rather the total for each individual post. Can anyone tell me what I have got wrong? How can I get total comment for each post?

I would try adding COUNT(*) in your initial SELECT. So your query would read
SELECT *, COUNT(*), AVG(rate)
FROM comments c
LEFT JOIN supps s
ON c.tutorialid = s.tutid
WHERE category = 'Protein'
GROUP BY tutorialid
ORDER BY $orderby $sort LIMIT $startrow,$limit";

Related

PHP SQL Query to get the most common value in the table

I'm trying to have my query count the rows and have it return the most common name in that list, then from that it counts how many times that name appears and outputs the name and the amount of times its there
This is the code I'm using:
$vvsql = "SELECT * FROM votes WHERE sid=? ORDER BY COUNT(*) DESC LIMIT 1";
$vvresult = $db->prepare($vvsql);
$vvresult->execute(array($_GET['id']));
$vvcount = $vvresult->rowCount();
foreach ($vvresult->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo $row['username'];
echo $vvcount;
}
However, it just displays the first username in the table and counts up the entire table. I'm pretty new to this so I'm sorry if this is a bad post or if it didn't make much sense.
You would seem to want:
SELECT name, COUNT(*) as cnt
FROM votes
GROUP BY name
ORDER BY COUNT(*) DESC
LIMIT 1;
Note the GROUP BY. You may also want to filter by sid but your question makes no mention of that.
select username, count(*) as c
FROM votes
GROUP BY username
ORDER BY c DESC

Using query with group_concat to loop values but show lowest price

I am using the query below to get all results and then then group them. It all works well. I now have multiple rows of identical data but with a different price.
How can I do the same query but get just the row with the cheapest price when all other data is identical. I have spent ages but no joy at all. Please help.
$results = $wpdb->get_results($wpdb->prepare("
SELECT *,
group_concat(date,':',SUBSTRING_INDEX(flights,'|',2),':',price,':',board,':',$tablename.id separator ',') as itemx
FROM $tablename
WHERE post_type = 'product'
GROUP BY brochure
LIMIT 20
"));
Presumably, you want something like this:
SELECT t.*,
FROM $tablename t
WHERE t.post_type = 'product' AND
t.price = (SELECT MIN(t2.price)
FROM $tablename t2
WHERE t2.post_type = 'product' AND
t2.brochure = t.brochure
);
This is at least a correctly constructed query that gets the minimum price for each brochure.

Pulling latest post from table

All,
I am trying to display the latest post from my authors.
The posts are in one table, the author in another. The queries used were: join on a column called content_id, and I am trying to work with MAX(item_date) which is the date the post was published.
Here are some queries I am running and the output, I seem to be getting everything except the latest posts from all authors:
First (and this bit is working) we need to get information about the author:
$query="SELECT content_id, title, source_image, url FROM content_detail where approved='y'";
$result1 = $mysqli->query($query) or die($mysqli->error.__LINE__);
// GOING THROUGH THE DATA
if($result1->num_rows > 0) {
while($fetch=mysqli_fetch_array($result1)) {
$title=$fetch['title'];
$feed_rss=$fetch['url'];
$content_id=$fetch['content_id'];
$source_image=$fetch['source_image'];
Now on that basis lets get the posts, round 1:
$query2 = "SELECT item_id, item_title, MAX(item_date) as item_date from posts WHERE content_id='$content_id' GROUP BY content_id";
$result2 = $mysqli->query($query2) or die($mysqli->error.__LINE__);
if($result2->num_rows > 0) {
while($rows2=mysqli_fetch_array($result2)) {
$item_id = $rows2['item_id'];
$item_title = $rows2['item_title'];
$item_date = $rows2['item_date']; `
This pulls back an in interesting set of results, the latest date of a post from an author, but not the latest title!
I have tried GROUP BY item_title and content_id to no avail.
The following pulls back just records that have more than one date in the database, the problem is (as this is new) some authors only have one post, these are not being displayed:
$query2 = "SELECT item_id, item_title, item_date FROM posts AS a WHERE content_id = content_id AND item_date = (
SELECT MAX(item_date)
FROM rssingest AS b
)
";
I have tried:
ORDER BY DATE DESC LIMIT 1
at the end of my queries to no avail.
item_date is a DATE type in the table.
Any help would be greatly appreciated!
Thanks,
You are running this query to get the maximum date:
SELECT item_id, item_title, MAX(item_date) as item_date
from posts
WHERE content_id = '$content_id'
GROUP BY content_id;
Of course you don't get the right item_title. It is not mentioned in the group by clause and has no aggregation function. So, you are using a MySQL extension (this query would fail in other databases).
You can get the most recent title using the substring_index()/group_concat() trick:
SELECT max(item_id),
substring_index(group_concat(item_title separator '|' order by item_date desc), '|', 1) as last_title,
MAX(item_date) as item_date
from posts
WHERE content_id = '$content_id'
GROUP BY content_id;
This will return one row. But, if there is only one row that you want, you can do:
SELECT p.*
from posts p
WHERE p.content_id = '$content_id'
ORDER BY item_date desc
LIMIT 1;
The previous version will generalize if you add a group by statement.
You need to join your posts table with itself to grab only the newest post for each content_id (which I believe is the author).
$query2 = "SELECT posts.item_id, posts.item_title, posts.item_date from posts
join (select max(item_id) max_id, content_id from posts group by content_id) maxid
on maxid.content_id=posts.content_id and maxid.max_id=posts.item_id
WHERE content_id='$content_id' ";
This opens the door for further optimization. You could grab the authors and their last post in one run.
SELECT content_detail.content_id,
content_detail.title,
content_detail.source_image,
content_detail.url ,
posts.item_id,
posts.item_title,
posts.item_date
FROM content_detail
join posts on content_detail.content_id=posts.content_id
join (select max(item_id) max_id, content_id from posts group by content_id) maxid
on maxid.content_id=posts.content_id and maxid.max_id=posts.item_id
where content_detail.approved='y'
But this could be an overstatement. You should of course try it yourself :)

mysql - how to count how many records there are in a table and then only get 20?

I'm building a forum for a school project and I want to display only say 20 posts per page, for a forum. However, I still need to know how much total posts there are, to display the page listing.
I could run a mysql query that limits the number of posts to 20, and then, run another query that would count how many records there are in a table, but that would be 2 queries. Isn't there a way to both get a limited number of records AND in the same query, to get the number of records total?
Thanks.
You can use a subquery
select *,
(select count(*) from your_table) as total_count
from your_table
order by some_column
limit 20
I'm expanding juergen's post:
$result = mysql_query("SELECT * (SELECT COUNT(*) FROM table) AS total FROM tablePRDER BY id LIMIT 0, 20");
while($row = mysql_fetch_assoc($result))
{
$total = $row['total']; /* Total rows of the whole table */
$id = $row['id']; /* Id of limitted query (20) */
}
select *
from your_table
inner join (select count(*) as total_count from your_table) tc
order by some_column
limit 20;

Returning Mysql result with COUNT( * )

I'm trying to return a count from mysql. My code is below
$number_of_options_sql = tep_db_query("SELECT COUNT( * ) FROM
(select sum(options_id) as total from products_attributes
where products_id='".$products_id."' group by options_id) as total");
$number_of_options_result = tep_db_fetch_array($number_of_options_sql);
When I run this query in Phpmyadmin, it shows the result with COUNT(*) at the table heading. I'm getting the correct result, the query works for me, I just can't print it out on the screen.
I've tried returning the value the following ways and neither print anything on the screen:
echo $number_of_options_result[COUNT( * )];
echo $number_of_options_result[total];
Use AS field_name after COUNT(*)
$number_of_options_sql = tep_db_query("SELECT COUNT(*) AS field_name FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) as total");
To print:
echo $number_of_options_result['field_name'];
(Replace "field_name" with any relevant name of your choice)
Your query is assigning an alias to the table/query not the column. use this one below:
$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) a");
$number_of_options_result = tep_db_fetch_array($number_of_options_sql);
Also looks like you want to know count of distinct options id for a product_id, I would rewrite the query as follows:
$number_of_options_sql = tep_db_query("SELECT COUNT(DISTINCT options_id) as total FROM products_attributes WHERE products_id='".$products_id."'");
Just edit your query to
SELECT COUNT(*) as count FROM ....
then it will be stored like 'count' and you can print it the $number_of_options_result[count]; way.
put in a variable "total"
$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total
then it works
echo $number_of_options_result['total'];

Categories