简体   繁体   中英

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 id s.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM