title: Getting latest value from database, checking value and applying itself in PHP
body: <p>I'm new to PHP so am not sure if I'm doing this right but can someone give it a second pair of eyes for me please?</p>
  
  <p>Basically what I want it is that we can define an initial start of an invoice number, in this example 00001 - if that is not found in the invoices table on latest entry then show 00001 else I need it to take the latest and add 1 onto the value to display when creating the next invoice. </p>
  
  <p>I guess it will need a condition so that if the actual table is empty as well as if no result to start at 00001</p>
  
  <p>PHP so far</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;input type="text" id="invoice_id" value="AMBMN&lt;?php getInvoiceId(); ?&gt;"&gt;
  </code></pre>
  
  <p>PHP:</p>
  
  <pre><code>// Initial invoice number
  function getInvoiceId() {
  
      define('INVOICE_INITIAL_VALUE', '00001');
  
      // Connect to the database
      $mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
  
      // output any connection error
      if ($mysqli-&gt;connect_error) {
          die('Error : ('. $mysqli-&gt;connect_errno .') '. $mysqli-&gt;connect_error);
      }
  
      $query = "SELECT invoice FROM invoices ORDER BY invoice DESC LIMIT 1";
  
      // mysqli select query
      $result = $mysqli-&gt;query($query);
  
      //Invoice length
      $invoice = $row['invoice'];
  
      if(!$result){
          echo INVOICE_INITIAL_VALUE;
      } else {
      // check if the initial invoice ID has already been used and if not start from that value else from the next value
          if($invoice != INVOICE_INITIAL_VALUE) {
              echo $invoice;
          } else {
              echo INVOICE_INITIAL_VALUE;
          }
      }
  
      // Frees the memory associated with a result
      $result-&gt;free();
  
      // close connection 
      $mysqli-&gt;close();
  
  }
  </code></pre>