简体   繁体   中英

PHP get the max value from database

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM