Return 来自 Table mysql 错误的最后一行
Return last row from a Table mysql Error
试图从数据库中获取最后一行,但是当 table 是新的并且没有输入任何行时,它 return 错误。
$lastrow="select ID from $sectionN order by ID desc limit 1";
$lastrow=mysql_query($lastrow);
echo $lastrow;
$lastrow=mysql_result($lastrow,0) + 1;
如何解决这个问题,即使 table 是新的也是 return 最后一行(我指的是第一行)
您可以使用 COALESCE
检查 ID
是否为 null
,然后 return 0
(或其他任何您想要的东西):
select COALESCE(MAX(uid), 0) from users
您可以简单地使用 MAX
来获取最后插入的 ID
,如果它将为空,则查询将 return 0
代替。
但我建议您在 table 的 ID 上使用 Auto Increment
。因为你不知道其他人是否也有那个 lastID + 1
值作为 ID。
更改您的查询并包含 WHERE
条件,例如
select ID from $sectionN
where ID is not null
order by ID desc limit 1
试图从数据库中获取最后一行,但是当 table 是新的并且没有输入任何行时,它 return 错误。
$lastrow="select ID from $sectionN order by ID desc limit 1";
$lastrow=mysql_query($lastrow);
echo $lastrow;
$lastrow=mysql_result($lastrow,0) + 1;
如何解决这个问题,即使 table 是新的也是 return 最后一行(我指的是第一行)
您可以使用 COALESCE
检查 ID
是否为 null
,然后 return 0
(或其他任何您想要的东西):
select COALESCE(MAX(uid), 0) from users
您可以简单地使用 MAX
来获取最后插入的 ID
,如果它将为空,则查询将 return 0
代替。
但我建议您在 table 的 ID 上使用 Auto Increment
。因为你不知道其他人是否也有那个 lastID + 1
值作为 ID。
更改您的查询并包含 WHERE
条件,例如
select ID from $sectionN
where ID is not null
order by ID desc limit 1