I would like to know if there is any way to know the first free record of mysql, but not the last one, if not the first free one that exists.
Ex:
I have busy registration 1,2,3,6,7,8,9 the first free one would be 5
At the moment I have a code that tells me the last one, which would be this:
$CIdmaxFact = "SELECT MAX(CAST(codfactura AS UNSIGNED)) AS ultimocod FROM Facturas WHERE empresa='".$_SESSION['Empresa_Id']."' AND serie='".$_POST["Infactura_serie"]."' "; //miramos de nuevo el ultimo codigo por si aca
$RIdmaxFact = mysqli_query($Conectar ,$CIdmaxFact); //pongo un resultado de la consulta
$DIdmaxFact=mysqli_fetch_array($RIdmaxFact); $idmaxFact = trim($DIdmaxFact["ultimocod"]); $idmaxFact ++;
$idmaxFact = str_pad($idmaxFact, 4, "0", STR_PAD_LEFT);
But it doesn't work for me at all, since it only tells me the last one. Any ideas?
You can use this little "trick"
I hope it helps you.
Someone asked a similar question here . And the accepted answer proposes some interesting solutions (I think that's where w33haa got its inspiration from), although they don't seem to me to handle every case correctly. For example, it will not handle the case when the code
1
is free.I propose the following adjusted solutions. To simplify the query, I'm going to assume it
codfactura
's numeric, even though it doesn't actually appear to be. You will have to add the casts where they are necessary:... or, using
min()
instead oforder by ... limit 1
: