Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last value from mysql record

Tags:

php

mysql

i'm php beginner please help me..

i have mysql record like bellow

id   name     value_1   value_2
 1   rakesh   100      50
 2   david    150      10
 3   richard   0       0
 4   michael   0       0  

I want last record value_1 to do some math But if last record value_1==0 means i want to go and get upper top value_1 (value_1=150)

i use bellow code but i get only last value

$get=mysql_query("SELECT MAX(id) FROM table_name ");
$got = mysql_fetch_array($get);
$next_id = $got['MAX(id)'];

here get 3d richard value_1==0 but i want 2nd david value_1 150

please help me thanks in advance...

like image 287
GreedenHolidays India Avatar asked Jan 14 '23 20:01

GreedenHolidays India


2 Answers

Your query is giving you the last row, because you are always selecting the biggest id.

Try with that:

SELECT * FROM table_name WHERE value_1 > 0 ORDER BY value_1 DESC LIMIT 1
  • It will select the whole row so you won't need to make an additional query.
  • WHERE value_1 > 0 will select only rows where value_1 is bigger than 0. It assumes that such records exists though. Let me know if this is not your case.
  • ORDER BY value_1 DESC tells the query to order the rows by value_1 in descending order and thus the desired row will be on top.
  • LIMIT 1 selects the first row only.
like image 71
Haralan Dobrev Avatar answered Jan 19 '23 12:01

Haralan Dobrev


Sounds like you want:

SELECT MAX(id) FROM table_name WHERE value_1 <> 0

Will select the maximum ID where value_1 is not 0

like image 27
juco Avatar answered Jan 19 '23 11:01

juco