Preserve 000 in a sum

1

I have the following code where I get the MAX of a code, but this code is a String . To this MAX I separate it in two to get the first 3 initials that are letters and in the numbers to add 1 to the numbers.

    $query  = "SELECT MAX(CodMaquina) FROM Maestro_Maquinas WHERE Centro_Costo = '$centro_costo'";
    $result = mysqli_query($conn, $query);
    $row    = mysqli_fetch_row($result);

    $numbers = preg_replace('/[^0-9]/', '', $row[0]);
    $letters = preg_replace('/[^a-zA-Z]/', '', $row[0]);
      $sumnumbers = $numbers+1;
    $codmaquina = $letters.$sumnumbers;
    echo   $codmaquina;

The initial value of row[0] is ELA0045 but the result is ELA46 . How can I keep the 00 or apply another formula to add.

    
asked by MoteCL 30.07.2018 в 17:18
source

2 answers

1

Your variable $ numbers contains the text string that corresponds to the number.

Therefore, all you have to do is use the str_pad function:

$query  = "SELECT MAX(CodMaquina) FROM Maestro_Maquinas WHERE Centro_Costo = '$centro_costo'";
$result = mysqli_query($conn, $query);
$row    = mysqli_fetch_row($result);

$numbers = preg_replace('/[^0-9]/', '', $row[0]);
$letters = preg_replace('/[^a-zA-Z]/', '', $row[0]);
$sumnumbers = $numbers+1;
$sumnumbers = str_pad($sumnumbers, strlen($numbers), '0', STR_PAD_LEFT);
$codmaquina = $letters.$sumnumbers;
echo   $codmaquina;

I hope it serves you. Greetings

    
answered by 30.07.2018 / 17:27
source
1

You can use the sprintf function with this format, it will always keep the 4 digits you need, adding 0's to the left when these figures are empty:

$sumnumbers = sprintf("%04s", $numbers+1);

Finally your code would look like this:

$query  = "SELECT MAX(CodMaquina) FROM Maestro_Maquinas WHERE Centro_Costo = '$centro_costo'";
$result = mysqli_query($conn, $query);
$row    = mysqli_fetch_row($result);

$numbers = preg_replace('/[^0-9]/', '', $row[0]);
$letters = preg_replace('/[^a-zA-Z]/', '', $row[0]);
echo   $numbers;
$sumnumbers = sprintf('%04s', $numbers+1);
$codmaquina = $letters.$sumnumbers;
echo   $codmaquina;
    
answered by 30.07.2018 в 17:27