0

Trying to get last row from a database, but when the table is new and no row is entered, it return error.

$lastrow="select ID from $sectionN order by ID desc limit 1"; 
$lastrow=mysql_query($lastrow);
echo $lastrow;
$lastrow=mysql_result($lastrow,0) + 1;

How to fix that so that even if the table is new it return last row (I mean first row in this case)

AK47
  • 11
  • 5

2 Answers2

0

You can use COALESCE to check if the ID is null, then return 0 (or something else whatever you want):

select COALESCE(MAX(uid), 0) from users

You can simply use MAX to get the last inserted ID, if it will be null the query will return 0 instead.

But I would suggest you to use Auto Increment on table's ID. Because you don't know if someone else also has that lastID + 1 value as ID.

Shaharyar
  • 12,254
  • 4
  • 46
  • 66
  • $empty ="select COALESCE(ID, 0) from $sectionN order by ID desc limit 1"; $queryempt=mysql_query($empty); – AK47 Jan 19 '16 at 16:02
  • How to put that in condition does $queryempty return 0 ? (if empty) – AK47 Jan 19 '16 at 16:04
  • Yes you did it fine, the query I provided will return `0` if there will be no row in table. – Shaharyar Jan 19 '16 at 16:05
  • $empty ="select COALESCE(ID, 0) from $sectionN order by ID desc limit 1"; $queryempt=mysql_query($empty) if ($queryempt = 0){ $lastrow = 1; } Else { $lastrow="select ID from $sectionN order by ID desc limit 1"; $lastrow=mysql_query($lastrow); echo $lastrow; $lastrow=mysql_result($lastrow,0) + 1; } – AK47 Jan 19 '16 at 16:08
  • No you don't need to do this `if-else` your code is fine, just replace the query and you're good to go. – Shaharyar Jan 19 '16 at 16:09
  • $lastrow="select COALESCE(ID, 0) from $sectionN order by ID desc limit 1"; $lastrow=mysql_query($lastrow); echo $lastrow; $lastrow=mysql_result($lastrow,0) + 1; Still get the same error Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 9 in C:\wamp\ – AK47 Jan 19 '16 at 16:13
0

Change your query and include a WHERE condition like

select ID from $sectionN 
where ID is not null
order by ID desc limit 1
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • I need to check with condition first if Id is null or not, so that if it is null return row 1 – AK47 Jan 19 '16 at 16:10