What PDO query should i use? - php

I have a table on my database which called topics(topic_id,topic_subject,topic_content,topic_date,topic_cat,topic_comm,topic_by,votes,tags,views,flags), from this table i want to echo
10 top users(topic_by) with the most topics(max number of topics) on a specific community(topic_comm). What PDO query should i use ? I think need something like below:
$sql = $conn -> prepare("SELECT topic_by WHERE topic_comm=:comm AND ( MAX COUNT(topic_id) )")

Let construct the query step by step. In order to get the top 10 user by most topic by community, you need to compute number of topic by each user on that community.
SELECT topic_by, COUNT(*) AS total_topic FROM topic
WHERE topic_comm = :comm GROUP BY topic_by
Then, you want to get the top 10 user, you can use basic subquery and LIMIT. So the final query
SELECT * FROM (
SELECT topic_by, COUNT(*) AS total_topic FROM topic
WHERE topic_comm = :comm GROUP BY topic_by
) AS t ORDER BY t.total_topic DESC LIMIT 10

Related

Fetching data with Group by, How to select the latest or greatest id? (PHP to MySQL)

I wanted to fetch data from MySQL with PHP when a user inputs something. I have this code.
$query = "SELECT * FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid";
$result = mysqli_query($con, $query);
It works fine however, it fetches the oldest or first data from the group. How do I select the newest data?
I've search and found possible solutions by using FROM, JOIN, IN, etc. However, I do not know how to use them since I only know the basics. Hopefully someone could explain one solution for me.
There is a simple solution that you can do.
You can order your data to DESC order. I'm sure that you have an id(primary key) in your table.You just have to order all your datas' to DESC order of ids .So that your last inserted data set will be the one to be fetched since it's on the top.
change your query to: (add your primary key(in the following query i have added it as id) in the ORDER BY syntax)
$query = "SELECT * FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid ORDER BY `ID` DESC"
Just add a condition in your query which only retrieves the row having the greatest id.
Find out the id first and then you can use the same query for that id:
SELECT MAX(id) FROM mealplans WHERE plantitle LIKE '%$inputText%' AND `STATUS` = 1 OR plantitle LIKE '%$inputText%' AND userid = '$userid' GROUP BY plantitle, userid
After getting the id and storing it in a variable (say $temp):
SELECT * from mealplans where `id` = $temp

how to select alternate rows from mysql using php

I want to select rows alternatively in mysql using php,
<?php
$result=mysql_query("select * from marker1 where date='$maxdate' and time BETWEEN '$mintime' AND '$maxtime' and imei_no='$vehicle_imei_no1'")or die(mysql_error());
?>
this is my query but it select all rows, in database i m not getting serialy data so i can't use this query
select t.id, name
from (select id, name, ROW_NUMBER() over (order by id) as srNo from Employee) t
where (t.srNo % 2) = 1
i only differentiate by time '11:05:30' in this formate
please guide me how to use query for alternative rows.
Thanks
Maybe this would work!:
select * from marker1 where date='$maxdate' and time BETWEEN '$mintime' AND '$maxtime' and imei_no='$vehicle_imei_no1'
AND (marker1.ID % 2) == 0
marker1.ID is the primary key and I'm supposing it as auto_increment.
This should select only the even values.
$sql = "SELECT * FROM Orders LIMIT 15, 10";
It would start from record 15th and return 10 records.
Ref: Link

SQL - Get number of rows WHERE "something = something" but not limited by LIMIT

So I had a pretty hard time describing this problem in the title, but basically I need to be able to get the number of rows my SQL query returns from the WHERE clause but is not limited by the LIMIT clause.
Example:
I have a table consisting of 10 posts. They all have column "show" = "true".
I then write my query like this:
$result = "SELECT * FROM table WHERE show = 'true' LIMIT 5";
I now need to get a variable on how many posts would be returned, had the LIMIT not been there.
$count = mysqli_num_rows($result); does not work as it'll only tell me 5 because of the LIMIT. I somehow need to know that there's 10 posts with column "show" = "true", even though my query only returns 5 posts because of the LIMIT.
Help would be very much appreciated!
Use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
select SQL_CALC_FOUND_ROWS t.*
from table t.*
where show = 'true'
limit 5;
Then:
select found_rows();
The documentation is here.
You can use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE show = 'true' LIMIT 5;
SELECT FOUND_ROWS();
http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_found-rows
Another option is to issue two distinct queries, one to get the first five (as you have already), and another to get the total count:
SELECT * FROM table WHERE show = 'true' LIMIT 5;
SELECT COUNT(*) FROM table WHERE show = 'true';

Single mysqli query statement to get total number of rows and limit also

I want to fetch the total count of records in MySQL db table and also use the limit with this. For example, there are 100 rows and the limit I want to use let suppose is 10. I know how to do this using two queries but I want to do this in one go.
SELECT count(*) as total_rows FROM mytable; // gets the total count of rows
SELECT col1,col2 FROM mytable LIMIT 0, 10; // gets the 10 rows of col1,col2
I want to do this in one go. Any idea.
Thanks.
Here is the SQL Fiddle that demonstrates how the below works:
SELECT m.*,
(
SELECT COUNT(*)
FROM mytable AS sm
) AS TotalCount
FROM (
SELECT mt.col1, mt.col2
FROM mytable AS mt
LIMIT 0, 10
) AS m
Have a look at Shayan Husaini's answer on How to get the total row count with MySQLi
I have updated his original answer after trying it out myself. You have to add "SQL_CALC_FOUND_ROWS" after SELECT in your query and add a second query as shown in the code snippet below.
$sql1 = "SELECT SQL_CALC_FOUND_ROWS col1,col2 FROM mytable LIMIT 0, 10";
$sql2 = "SELECT FOUND_ROWS()";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$TotalRcount = $result2->fetch_row();
// I have added this next line to correct the answer
$TotalNumRows = $TotalRcount[0];
You can use $result1 to access your results as you normally would.

SQL for sorting out next/previous picture in gallery

I'm working on the photo section of my website, but more precisely on the next/previous link with sorting options.
There are two different option for sorting that exist, first there is a filter (Latest, Trending, Favorite, User etc.) and secondly a sorting option for some of the previous filters (date, views, ratings etc.)
I am having trouble finding a good solution for easily retrieving the next/previous picture for my slideshow.
This is the little bit of SQL I have for getting the next picture for a filter:latest
if ($filter == "latest") {
$sql = "SELECT *
FROM photos
WHERE status = 0 AND id < ".$id."
ORDER BY id DESC
LIMIT 1
";
$result = $db->sql_query($sql);
$sql2 ="SELECT *
FROM photos
WHERE id = (SELECT MAX(id) FROM photos WHERE status = '0')
ORDER BY id DESC
LIMIT 1
";
}
I am wondering if there is an easier way to implement this in my project ? maybe a php class exists to do something like this ?
I feel like I'm going to spend a long time getting all these SQL queries to work properly if I have to do it all like this.
Edit
This is the layout of my photos table
`id` -> unique ID, autoincremented
`title`
`img_name` -> contains the image file name
`date_created` -> when the picture was uploaded
`uploader` -> id of the user that uploaded
`views` -> number of views the picture has
`up_votes` -> votes used to calculate the Wilson score interval
`down_votes`
`net_votes` -> up vote minus down votes
There are other tables like one that links user with friends they have, it is called users_friends
`user_id` -> contains id of the user that added the friend
`friend_user_id` -> contains id of the friend in question
With these two tables I am able to get all the pictures posted by the friend of a user using this sql query :
SELECT *
FROM photos
WHERE uploader IN
(
SELECT friend_user_id
FROM users_friends
WHERE user_id = ':user_id'
)
ORDER BY id DESC
I then have two queries to get the link to the next picture and 2 other queries for the previous one. I have two because one is for when you get at the end of the database to go back to the other end and the other one is for all the other queries. And they look something like this (I'm only posting the next button here)
$sql = "SELECT *
FROM photos
WHERE status = 0 AND id < ".$id." AND Uploader IN (SELECT friend_user_id FROM users_friends WHERE user_id = ".$logedInUser['User_ID'].")
ORDER BY id DESC
LIMIT 1
";
$sql2 ="SELECT *
FROM photos
WHERE id = (SELECT MAX(id) FROM photos WHERE status = '0' AND Uploader IN (SELECT friend_user_id FROM users_friends WHERE user_id = ".$logedInUser['User_ID']."))
ORDER BY id DESC
LIMIT 1
";
$result = $db->sql_query($sql);
if (mysql_num_rows($result)==1) {
$row = $db->sql_fetchrow($result);
return "/photo/".$row["id"]."/".urlFriendly($row["Title"])."/".$filter.$sort;
}
else
{
$result = $db->sql_query($sql2);
$row = $db->sql_fetchrow($result);
return "/photo/".$row["id"]."/".urlFriendly($row["Title"])."/".$filter.sort;
}
I feel like there is a lot of stuff that could be simplified, but I don't yet know how to do it.
I also have the Lower bound of Wilson score sql code to implement for the next/previous button, and it is quite a bit sql code to have to write 4 time. Maybe that I can insert the Wilson score in the photos table, which could simplify a lot the sql code.
It would be helpful if you could post the structure of your table - i.e. what columns/types you have and what each row represents. I'll assume that you have a table where each row represents a photo, and that each photo has an ID, filename, and various other columns that help you filter/sort (such as date, favorite, etc.).
If your filtering and sorting preferences are defined by the user, you can then use those in a single SQL query, whereby you get the full set of ordered results. For instance:
$sort = date;
$filter = favorite;
$sql = "SELECT ID, filename, [other vars here]
FROM photos
WHERE " . $filter . " = TRUE
ORDER BY ". $sort . " DESC";
$result = $db->sql_query($sql);
Now, you can use a function such as mysql_fetch_array to step through each row in your result set and populate some kind of data structure with the current, previous, and next photos.

Categories