1

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.

Ahamed
  • 59
  • 3
  • 9
  • 2
    What's wrong with using three lines? I'd be more concerned about the error suppression usage. – chris85 Feb 10 '17 at 19:38
  • It's not wrong, one line does the query, other fetches the result, and then you show... you can change the last 2 lines with this `$getlastID = mysqli_fetch_row($result)[0];` but this depends on your PHP version. Obviously you can put the `mysqli_query` inside `mysqli_fetch_row(HERE)` and have all one line. – matiaslauriti Feb 10 '17 at 19:39
  • Their is nothing wrong using three line of code. However I just want to reduce the amount of code as possible as I can. – Ahamed Feb 10 '17 at 19:40
  • If you want to reduce code, use OOP. – matiaslauriti Feb 10 '17 at 19:41
  • If you want to reduce the amount of code, then either declare a function that perform these three steps (see [this thread for details](http://stackoverflow.com/questions/11456707/single-value-mysqli)) or use a DB library that will do it for you. – Jirka Hrazdil Feb 10 '17 at 19:42
  • i am curious to why you want to reduce number of lines. It is horrible practice, especially if you are going to show your code to others or have them maintain it. – Dimi Feb 10 '17 at 20:06

1 Answers1

0

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.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80