How to find no of rows with same value in php mysql - php

I have one table with event_id & image_id. I want to find the no of rows which with the same value -> max in this table.
means in this table output should like:
1508706279 -> image_id
4 -> no of rows
here is my table.
below is the code which i have tried.
$sql2 = "select image_id, COUNT(*) as count from user_likes where event_id = '$id' GROUP BY image_id";
if($result2 = mysqli_query($conn, $sql2)) {
$result1 = mysqli_fetch_array($result2);
$win = $result1['image_id'];
$count = $result1['count'];
}
Now, i can't understand what is issue but this code works fine when there are rows between id 52 to 60
it shows output:
1508706279 -> image_id
4 -> no of rows
but when i add two more rows with id 64 & 65
it shows output:
818525590 -> image_id
1 -> no of rows
help me in this what mistake i am doing here.!!

Your query return a collection of image_id and count.
The collection is not ordered so you have the first one from select
if you need the max try ordering by count(*) desc
$sql2 = "select image_id, COUNT(*) as count
from user_likes
where event_id = '$id'
GROUP BY image_id
ORDER BY count(*) DESC";
and you can limit to 1 if you need one row only
$sql2 = "select image_id, COUNT(*) as count
from user_likes
where event_id = '$id'
GROUP BY image_id
ORDER BY count(*) DESC LIMIT 1";

Related

How to fetch specific column values have more than x rows in php?

In my MySQL 'purchase' table one column stores user_name, as every finished purchase is stored here along with other details such as shopping_cart_id, amount, i want to fetch what are the user_name have more than 10/50/100 purchases.
I can get the number of purchase record for every users, but i want to filter the results by number of rows. Here is my query for getting the number of records for every user.
$query = MySQL_query("SELECT user_name, COUNT(*) as count FROM purchase GROUP BY user_name ORDER BY count DESC") or die(MySQL_error());
thanks
Use HAVING clause
SELECT user_name,
COUNT(*) as count1
FROM purchase
GROUP BY user_name
HAVING COUNT(*) IN (100, 50, 10)
ORDER BY count1 DESC
(OR) Use a outer select and filter the same like
SELECT * FROM
(
SELECT user_name,
COUNT(*) as count1
FROM purchase
GROUP BY user_name ) xx
WHERE count1 IN (100, 50, 10)
ORDER BY count1 DESC
I added an if statement within my while loop and it worked fine. I know there many more ways to achieve this result. My code:
$query = MySQL_query("SELECT user_name, COUNT(*) as count FROM purchase GROUP BY user_name ORDER BY count DESC") or die(MySQL_error());
while($row = mysql_fetch_array($query))
{
$user_name = $row["user_name"];
$num_rows = $row['count'];
if($num_rows > '100'){
echo $user_name." – ".$num_rows."<br>";
}
}
This code retrieved all user_name who have more than 100 purchases, from higher to lower.

SQL Order By id and Count star not working

I would like to get number of all records and get last record :
$sql_count_sms = "SELECT count(*) as total,content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
$result_count_sms = mysql_query($sql_count_sms);
$row_num_sms = mysql_fetch_assoc($result_count_sms);
$num_sms = $row_num_sms['total'];
$last_my_sms = $row_num_sms['content'];
I can get number of records but I can't get last content record .
It returns first record !
Where is my wrong ?
Below codes works fine, but I think count(*) is faster than mysql_num_rows .
$sql_count_sms = "SELECT content,id FROM android_users_sms WHERE user_id=$id ORDER BY id DESC";
$result_count_sms = mysql_query($sql_count_sms);
$row_num_sms = mysql_fetch_assoc($result_count_sms);
$num_sms = mysql_num_rows($result_count_sms);
$last_my_sms = $row_num_sms['content'];
Any solution?
The grain of the two results you want is not the same. Without using a sub-query you can't combine an aggregate and a single row into the same result.
Think of the grain as the base unit of the result. The use of GROUP BY and aggregate functions can influence that "grain"... one result row per row on table, or is it grouped by user_id etc... Think of an aggregate function as a form of grouping.
You could break it out into two separate statements:
SELECT count(*) as total FROM android_users_sms WHERE user_id = :id;
SELECT * FROM android_users_sms WHERE user_id = :id ORDER BY id DESC LIMIT 1;
Also, specific to your question, you probably want a LIMIT 1 in combination with the ORDER BY to get just the last row.
Now, counter intuitively perhaps, this should also work:
SELECT count(*), content, id
FROM android_users_sms
WHERE user_id = :id
GROUP BY id, content
ORDER BY id
LIMIT 1;`
This is because we've changed the "grain" with the GROUP BY. This is the real nuance and I feel like this could probably be explained better than I am doing now.
You could also do this with a sub query like so:
SELECT aus.*,
(SELECT count(*) as total FROM android_users_sms WHERE user_id = :id) AS s1
FROM android_users_sms AS aus
WHERE user_id = :id ORDER BY id DESC LIMIT 1;

Deleting older database entries

I'm trying to keep the 10 most recent entries in my database and delete the older ones. I tried DELETE FROM people ORDER BY id DESC LIMIT $excess, but it just deleted the top 10 entries.
$query = "SELECT * FROM people";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count > 10) {
$excess = $count - 10;
$query = "DELETE FROM people WHERE id IN(SELECT id FROM people ORDER BY id DESC LIMIT '$excess')";
mysqli_query($conn, $query);
}
You can use this:-
DELETE FROM `people`
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM `people`
ORDER BY id DESC
LIMIT 10
)
);
Also your query is logically incorrect and you are fetching the records in descending order. i.e. Latest to older and you are deleting the most recent records. Use ASC instead.
Something like this? Gets the ten latest ids in the subquery, then deletes all of the other ids.
DELETE FROM people WHERE id NOT IN (SELECT id FROM PEOPLE ORDER BY id DESC LIMIT 10)
Your logic is all over the place, [you should ORDER BY ASC, not DESC] and your query will take ages if there are [for example] 10,000 entries because you'll have an IN clause with 9,990 entries to compare all 10,000 to.
Select the 10 most recent, and delete where NOT in.
DELETE FROM people
WHERE id NOT IN(
SELECT id
FROM people
ORDER BY id DESC
LIMIT 10
)
Maybe find the ID of the 10th element and then delete all rows which are older?

Sorting mysql results by times from 3 tables

I have 3 tables: questions, articles and pictures
The rows in each table contain a current_timestamp column posted, and link to an id. I'd like to sort the results of the rows of all three by their timestamp and only echo the newest of the three (for example: if the question is newest from the ID, display that only)
if(count($interests) != 0){ foreach($interests as $interests_following){
$interestid = mysql_result(mysql_query("SELECT `id` FROM `interests` WHERE `name` = '$interests_following'"),0);
$interestquestions = #mysql_result(mysql_query("SELECT `question_text`, `posted` FROM `questions` WHERE `interest` = '$interests_following'"),0);
$interestarticles = #mysql_result(mysql_query("SELECT `article_title`, `posted` FROM `articles` WHERE `interest_id` = '$interestid'"),0);
$interestpictures = #mysql_result(mysql_query("SELECT `interest_pic_title`, `posted` FROM `interest_pictures` WHERE `interest_id` = '$interestid'"),0);
echo '.$interests_following.': //<Only display 1 newest item (article/picture/question here>
Use UNION ALL:
SELECT posted
FROM
(
SELECT `question_text`, `posted` FROM `questions`
WHERE `interest` = '$interests_following'
UNION ALL
SELECT `article_title`, `posted` FROM `articles`
WHERE `interest_id` = '$interestid'
UNION ALL
SELECT `interest_pic_title`, `posted` FROM `interest_pictures`
WHERE `interest_id` = '$interestid'
) t
ORDER BY posted DESC LIMIT 1
To get a single row back:
$sql = "SELECT * FROM WHERE `name`='$interests_following' ORDER BY `posted` DESC LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
All of the work is in the SQL
ORDER BY `posted` DESC LIMIT 1
This orders results to have the newest first, then only return the first row.
If you mean to return only one item out of the 3 tables, you have 2 choices:
Fetch a row from each and then determine the newest in PHP
Use a UNION to find the single newest row in SQL
The latter makes for less code, but will probably be less readable.
try this
$interestquestions = #mysql_result(mysql_query("SELECT `question_text`, `posted` FROM `questions` WHERE `interest` = '$interests_following' ORDER BY timestamp_field DESC limit 1"),0);
this will show only the latest data base on your timestamp.
I'll show you the SQL queries so you can see what I did; adapt it to your code as needed.
SELECT
(SELECT question_text
FROM questions ORDER BY posted DESC LIMIT 1 ),
(SELECT article_title
FROM articles ORDER BY posted DESC LIMIT 1 ),
(SELECT interest_pic_title
FROM interest_pictures ORDER BY posted DESC LIMIT 1)
;
This sorts by the timestamp DESCending, so the latest record is first, then limits it to the single record. The result will be question_text, article_title, interest_pic_title.

MYSQL Select from table, get newest/last 10 rows in table

What's the best, and easiest way to do this? My query currently is:
SELECT *
FROM chat
WHERE (userID = $session AND toID = $friendID)
OR (userID = $friendID AND toID = $session)
ORDER BY id
LIMIT 10
This shows the first 10 rows though, not the last 10.
EDIT: I Want the last 10 rows (Which yes, DESC does this) However I want them to be returned in ASCENDING order.
to reverse the order (therefore get last 10 instead of first 10), use DESC instead of ASC
EDIT
Based on your comment:
SELECT * FROM (
SELECT *
FROM chat
WHERE (userID = $session AND toID = $friendID)
OR (userID = $friendID AND toID = $session)
ORDER BY id DESC
LIMIT 10
) AS `table` ORDER by id ASC
If you want the last 10 then just change ASC to DESC
SELECT *
FROM
chat
WHERE
(userID=$session AND toID=$friendID)
OR
(userID=$friendID AND toID=$session)
ORDER BY id
DESC
LIMIT 10
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$limit = 10;
$query = "SELECT * FROM $table";
$resource = mysqli_query($con,$query);
$total_rows = mysqli_num_rows($resource);
$start = $total_rows-$limit;
$query_limit= $query." LIMIT $start,$limit";
First I have set the limit
$limit = 10;
then
$total_rows = mysqli_num_rows($resource);
Here I have taken total number of rows affected.
$start = $total_rows-$limit;
then substracted limit from number of rows to take starting record number
$query_limit= $query." LIMIT $start,$limit";
and then added limit to the query.
For more information about limit see this link
https://www.w3schools.com/php/php_mysql_select_limit.asp
First select the last 10 from the table, then re-order them in ascending order.
SELECT * FROM (SELECT * FROM table ORDER BY id DESC LIMIT 10) sub ORDER BY id ASC

Categories