Help with auto-increase search

0

HELLO friends a consultation: I have an inventory table

id    codigo   descripcion
01    12345001  envase
02    12346001  caja
03    12345002  envase
04    12346002  caja

I am making an entry form for new items to the inventory where with the help of a catalog I look for container 12345 and then when I save I want it to increase to one more bone 12345003, it is trying with this sentence but it does not come out:

$codigo=$_POST['codigo'];
$e=mysqli_query($db,"SELECT MAX(codigo) FROM detalleinventarioinicial  where substr(codigo,1,5)='$codigo' GROUP by descripcion");
$d=(int) $e;
mysqli_query($db, "INSERT INTO inventario(id,codigo,descripcion) VALUES ('$id','$d','$descripcion')"); 
    
asked by deivid7777 15.08.2017 в 02:58
source

1 answer

0

You need to get the result of the query before using it and also add the +1 to select the next value; try this:

$codigo = mysqli_real_escape_string($db, $_POST['codigo']);
$e=mysqli_query($db,"SELECT MAX(codigo) +1 max FROM detalleinventarioinicial  where substr(codigo,1,5)='$codigo' GROUP by descripcion");
$d=mysqli_fetch_assoc($e);
mysqli_query($db, "INSERT INTO inventario(id,codigo,descripcion) VALUES ('$id','$d[max]','$descripcion')"); 

The other option is to embed the selection in the insert:

mysqli_query($db, "INSERT INTO inventario(id,codigo,descripcion) VALUES ('$id', (SELECT MAX(codigo) + 1 FROM detalleinventarioinicial  where substr(codigo,1,5)='$codigo' GROUP by descripcion") ,'$descripcion')"); 
    
answered by 15.08.2017 / 04:03
source