简体   繁体   中英

How to concatenate php variable with mysql function result in INSERT statement

is there any way to concatenate a php variable with a mysql function result in a insert statement?

I have the following code:

$conn = new mysqli("localhost", "root", "", "facturas");

$currDate = date("Y/m/d");

$currYear = date("y");

$S = "SELECT num_factura FROM facturas WHERE num_factura";

if($currYear > date("y")) {
    $sql = "INSERT INTO facturas (anyo, num_factura) VALUES ('$currDate', '".$currYear.(1)."')";
} else {
    if($conn->query($S)->num_rows > 0) {
        $sql = "INSERT INTO facturas (anyo, num_factura) VALUES ('$currDate', (SELECT MAX(h1.num_factura)+1 FROM facturas h1))";
    } else {
        $sql = "INSERT INTO facturas (anyo, num_factura) VALUES ('$currDate', '".$currYear.(1)."')";
    }
}

I want to concatenate the $currYear variable with the SELECT(MAX) function, I have tried '".$currYear."(SELECT MAX(h1.num_factura)+1 FROM facturas h1)' but it doesnt work the way I want to, which is incrementing the max column num_facturas by 1 concatenated with the $currYear variable.

You need to make the query first

(SELECT MAX(h1.num_factura)+1 FROM facturas h1))

and then you can concatenate the result to your original string.

$sql = "INSERT INTO facturas (anyo, num_factura) VALUES ('$currDate', '$maxNumFactura')";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM