Mysql Auto-increment conditioned to a table column

1

Hello,

I'm trying to create a vehicle table that looks like this with php and mysql:

+----+-----------------+-------+--------+
| id | nome do veiculo | marca | codigo |
| 1  | Gol             | VW    | 1      |
| 2  | Golf            | VW    | 2      |
| 3  | Fox             | VW    | 3      |
| 4  | Palio           | Fiat  | 1      |
| 5  | Argo            | Fiat  | 2      |
+----+-----------------+-------+--------+

Where id has the auto increment and the code would be added according to the brand vehicle number.

Ex: If you entered another car from vw it would receive id 6 and code 4. If it were fiat you would get id 6 only code 3.

I tried to make the value of the code as follows:

$ selveiculos = mysqli_query ($ connection, "SELECT id FROM vehicles where mark = '$ mark'");         $ codveiculo = 1 + mysqli_num_rows ($ selveiculos);

Where I check the number of vehicles of an X mark and make the code the number returned.

My problem is that I'm getting vehicle data with a $ .ajax function that is already passed to that php code to insert into the bank. So what's happening is to create equal codes for vehicles of the same brand.

Would you like to create the id with auto-increment and the code with an auto-increment but relating to the brand?

Any suggestions for resolving this?

Thank you

    
asked by anonymous 20.09.2017 / 20:03

1 answer

1

You can not have an AUTOINCREMENT field with two equal values. One solution would be a query to get the next id of that tag

SELECT MAX(codigo)+1 AS proximo_codigo WHERE marca = :IDMARCA
    
20.09.2017 / 22:45