1

Can anyone please help me? I'm a newbie on PHP so please understand. Here's my code.

$query="SELECT MAX(mid) as mid, ticketno FROM tbl_message GROUP BY ticketno";
$result=mysql_query($query);
while($row = mysql_fetch_array($result)){ 
echo $row['mid'];
echo $row['ticketno'];
}

DISPLAYS THIS

 - mid    ticketno
 - 2-------21510
 - 1-------24693
 - 4-------24693

WHAT I WANT

 - mid    ticketno
 - 2-------21510
 - 4-------24693

My database :

enter image description here

shin
  • 3,491
  • 1
  • 12
  • 17
  • 1
    Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 04 '15 at 13:07
  • 1
    Does your query, with GROUP BY, really return ticketno 24693 twice?!? – jarlh May 04 '15 at 13:14
  • @Jay thank you for informing me. I will on my next project. I dont want to re code again – shin May 04 '15 at 13:15
  • are you storing the ticketno as varchar or as an integer? – Jonathan May 04 '15 at 13:17
  • as varchar. my 'mid' is auto incremental – shin May 04 '15 at 13:18
  • 1
    Why varchar for ticketno? – jarlh May 04 '15 at 13:20
  • will it help me get what i want if its a integer ? – shin May 04 '15 at 13:23
  • how does the program know you don't want `1-------24693`? what is that logic? – KM. May 04 '15 at 13:27
  • OMG It worked !!! @jarlh. im sorry i didnt know !! why – shin May 04 '15 at 13:27

3 Answers3

5

Use ORDER BY . Try with -

$query="SELECT mid, ticketno FROM tbl_message GROUP BY ticketno ORDER BY mid DESC";
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
1
SELECT t.*
FROM tbl_message t
WHERE NOT EXISTS ( SELECT 'a'
                   FROM tbl_message t2
                   WHERE t2.ticketno = t.ticketno
                   AND t2.mid > t.mid
                  )
Javaluca
  • 859
  • 1
  • 6
  • 13
0

Okay so basically I just changed varchar to int (type of TICKETNO) then it returns the most latest ticketno.

I used this query

$query="SELECT MAX(mid) as mid, ticketno FROM tbl_message GROUP BY ticketno";

i used MAX() to return only the latest ticket no and GROUP BY ticketno so that it would return the other unique ticket no.

I guess varchar reads spaces.

shin
  • 3,491
  • 1
  • 12
  • 17