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.

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

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案