duanjian7343 2017-02-10 19:34
浏览 83
已采纳

PHP从数据库中获取最大值

Hey I am trying to get the max id from in my database using a one line of code.

Have this code that is working, however I know that there is a better way to do without using three line of code. One more thing I am using xammp for my database.

$result = @mysqli_query($connection, "SELECT MAX(Cust_ID) FROM customer");
$row = mysqli_fetch_row($result);
$getlastID = $row[0];

I was hoping that someone can help me, please.

  • 写回答

1条回答 默认 最新

  • douchuanghan1344 2017-02-10 20:10
    关注

    The fact is, with mysqli there are three steps to what you are doing. If you were using PDO, you could use fetchColumn to combine the last two steps into one.

    Just for the sake of argument, you can actually combine those three lines of code into one, by wrapping the query in the fetch row and dereferencing the result directly:

    $id = mysqli_fetch_row(mysqli_query($connection, 'SELECT MAX(Cust_ID) FROM customer'))[0];
    

    I would not recommend doing it this way, though. It will be easier to debug your script if each of these instructions is executed in a separate statement. Less code is generally better, but not at the expense of maintainability.


    Incidentally, you should avoid using the error control operator (@). If there are errors, you want to know about them so you can handle them rather than ignoring them. There may be some valid uses for it, but this is probably not one of them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码