Generate consecutive id number with annual restart in PHP

0

I have the following code,

<?php
session_start();
/* Inicia validacion del lado del servidor */
if (empty($_POST['sheets'])) {
    $errors[] = "Hojas vacío";
} else if (empty($_POST['title'])) {
    $errors[] = "Asunto vacío";
} else if (
        !empty($_POST['sheets']) &&
        !empty($_POST['title'])
) {

    include "../config/config.php"; //Contiene funcion que conecta a la base de datos        

    $title = $_POST["title"];
    $description = $_POST["description"];
    $sender_id = $_POST["sender_id"];
    $kind_id = $_POST["kind_id"];
    $user_id = $_SESSION["user_id"];
    $project_id = $_POST["project_id"];
    $category_id = $_POST["category_id"];
    $priority_id = $_POST["priority_id"];
    $status_id = $_POST["status_id"];
    $attach_id = $_POST["attach_id"];
    $hojas = $_POST["sheets"];
    $created_at = "NOW()";
//                $asigned_id = $_SESSION["asigned_id"];          
//                $publico = $_POST["publico"];
    // $user_id=$_SESSION['user_id'];

    $sql = "insert into document (title,description,sender_id,kind_id,user_id,project_id,category_id,priority_id,status_id,attach_id,sheets,created_at) value (\"$title\",\"$description\",\"$sender_id\",$kind_id,$user_id,\"$project_id\",\"$category_id\",$priority_id,$status_id,$attach_id,$hojas,$created_at)";

    $query_new_insert = mysqli_query($con, $sql);
    if ($query_new_insert) {
        $messages[] = "Tu documento ha sido ingresado satisfactoriamente.";
    } else {
        $errors [] = "Lo siento algo ha salido mal intenta nuevamente." . mysqli_error($con);
    }
} else {
    $errors [] = "Error desconocido.";
}

if (isset($errors)) {
    ?>
  <div class="alert alert-danger" role="alert">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <strong>Error!</strong>
    <?php
        foreach ($errors as $error) {
            echo $error;
        }
        ?>
  </div>
  <?php
}
if (isset($messages)) {
    ?>
    <div class="alert alert-success" role="alert">
      <button type="button" class="close" data-dismiss="alert">&times;</button>
      <strong>¡Bien hecho!</strong>
      <?php
        foreach ($messages as $message) {
            echo $message;
        }
        ?>
    </div>
    <?php
}
?>

The Id field of the table is incremental, but I also need this ID to be saved with the year, but every year restart the Id and change the year

2017-00280 that is left like this now

and the other year start like this

2018-00001

    
asked by 03.10.2017 в 23:34
source

2 answers

0

To create a code like that, you need to pre-query and get the number of records for the current year. Then you increase and place the necessary format:

<?php 
    // consulta que cuenta los registros del año actual
    $result = query_result("select count(*) as cont from document where year(created_at)=year(now())");
    $cont = $result->cont + 1; //incrementas
    $num = sprintf("%'.05d", $cont); // formato con 5 digitos
    $codigo = date("Y")."-".$num; // concatenas con el año actual
    echo $codigo;
?>
    
answered by 06.10.2017 / 20:06
source
0

Working on this type of thing with text files is a bad idea, but it is only to illustrate the steps to follow.

Assuming that you are working with a text file, save year, a separation character and the counter, example: 2017 | 123.

// Obtienes el año actual
$year = date('Y');
// Obtienes datos del archivo
list($cYear, $cCount) = explode('|', file_get_contents('counter.txt'));
if($year == $cYear) {
    // Si el año almacenado es el actual, entonces tomas el valor e incrementas
    $cCount ++;
} else {
    // De lo contrario, hay que actualizar año y reiniciar contador
    $cYear = $year;
    $cCount = 1;
}
// Actualizas los datos
file_put_contents('counter.txt', "$cYear|$cCount");
// Continúas con la ejecución de tu script, sabiendo que:
// Año = $cYear y Contador = $cCount

It is better if you work with database to avoid file read / write problems, mainly when there are several users accessing at the same time.

    
answered by 04.10.2017 в 07:11