Madtin
Madtin

Reputation: 109

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.

Upvotes: 0

Views: 1212

Answers (1)

mmucito
mmucito

Reputation: 134

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')";

Upvotes: 3

Related Questions