mysql如果while和else造成麻烦

时间:2018-04-19 21:36:14

标签: php html mysql database

我需要显示3种不同发票类型的最后发票编号,如果有发票,系统只需在发票编号上加+1,或者如果有第一张发票,则只需添加0000000001作为第一张发票号。

    <option value="boleta" data-price="
<?php $boletas=mysqli_query($datacenter, "
SELECT * FROM ventas 
WHERE documento = 'boleta' 
ORDER BY id DESC LIMIT 1");
while($boleta=mysqli_fetch_assoc($boletas)) 
    if(mysqli_num_rows($boletas) > 0) { echo
        str_pad($boleta['folio']+1, 15, "0", STR_PAD_LEFT);
    }
 else {
    echo "000000000000001";
}?>">boleta</option>
    <option value="factura" data-price="
<?php $facturas=mysqli_query($datacenter, "
SELECT * FROM ventas WHERE documento = 'factura' 
ORDER BY id DESC LIMIT 1");
while($factura=mysqli_fetch_assoc($facturas)) 
    if(mysqli_num_rows($facturas) > 0) { echo
        str_pad($factura['folio']+1, 15, "0", STR_PAD_LEFT);
    }
 else {
    echo "000000000000001";
}?>">boleta</option>
    <option value="nota" data-price="
<?php $notas=mysqli_query($datacenter, "
SELECT * FROM ventas WHERE documento = 'nota' 
ORDER BY id DESC LIMIT 1");
while($nota=mysqli_fetch_assoc($notas)) 
    if(mysqli_num_rows($notas) > 0) { echo
        str_pad($nota['folio']+1, 15, "0", STR_PAD_LEFT);
    }
 else {
    echo "000000000000001";
}?>">boleta</option>

当我只运行1个查询时,它可以工作并显示正确的数据但是当我尝试查询3个查询时,它只显示任何数据,但只显示在第一个<option>

修改

ELSE无效

1 个答案:

答案 0 :(得分:0)

尝试更改此内容:

$boletas=mysqli_query($datacenter, "
SELECT * FROM ventas 
WHERE documento = 'boleta' 
ORDER BY id DESC LIMIT 1");
while($boleta=mysqli_fetch_assoc($boletas)) 
    if(mysqli_num_rows($boletas) > 0) { echo
        str_pad($boleta['folio']+1, 15, "0", STR_PAD_LEFT);
    }
 else {
    echo "000000000000001";
}

要:

$sql = "SELECT * FROM ventas WHERE documento = 'boleta' ORDER BY id DESC LIMIT 1";
if ($boletas = mysqli_query($datacenter, $sql)) {
    if ($boleta = mysqli_fetch_assoc($boletas)) {
        echo str_pad($boleta['folio']+1, 15, "0", STR_PAD_LEFT);
    }
    else {
        echo "000000000000001";
    }
}
else {
    echo "Query failed for boletas!";
}

这是更具可读性,包括一些错误检查,如果没有结果,将显示所需的发票号000000000000001

顺便说一下,由于您使用的不同查询的性质,我不认为使用单个查询对您的问题非常实用。无论如何,最终还是需要3个子查询。