Insert field php concatenating date

1

I would like to know how to insert the following combination, via PHP or mysql:

I have a field called YEAR that needs to receive the current YEAR 2017 format via php or mysql.

I have a code field that will need to concatenate the protocol number + year, but this protocol would be the ID field of the table that is automatically generated with AI.

How would I get this ID, even if I had not generated any fields yet, since it is auto_increment.

In short, when making a new registration, it would take the ID + year and put it inside the CODE field.

    
asked by anonymous 21.08.2017 / 16:21

2 answers

2

Simple with a function, the code you want will be saved in the code code and then you can insert the code into the database:

Obs the id comes from the database and as it is a code I suppose it should be unique then the id you pass in the function must also be unique

// $id = $mysql['id'] provem da DB

function generateCode($id){

    //pegar ultimo registo
    $ultimoRegisto = $db->executar("SELECT id FROM denuncia ORDER BY id DESC LIMIT 1"); 

    //verifica a data do ultimo registo se 
    //for igual a data atual, incrementa se não começa denovo com valor 1
    if($ultimoRegisto->num_rows['ano'] == date('Y')){
        return $id . date('Y');
    }

    return 1 . date('Y');
}
    
21.08.2017 / 16:36
0

To do it right in MySql, you can do so. For example, I created a simple table, containing only ID (auto_increment) and CODE (to concatenate). INSERT looks like this:

INSERT INTO tb_teste (codigo) 
    VALUES (
       CONCAT(
           YEAR(NOW()),"-", (
                SELECT AUTO_INCREMENT
                    FROM information_schema.tables
                    WHERE table_name = 'tb_teste'
                    AND table_schema = DATABASE()
                )
        ));

See the result for this example. I made 3 insert's:

Just set CONCAT to the pattern you want.

    
21.08.2017 / 16:39