如何在INSERT语句中连接php变量和mysql函数结果

时间:2017-08-15 17:47:49

标签: php mysql concatenation

有没有办法在插入语句中将php变量与mysql函数结果连接起来?

我有以下代码:

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

我想将$ currYear变量与SELECT(MAX)函数连接起来,我已经尝试过'"。$ currYear。"(SELECT MAX(h1.num_factura)+1 FROM facturas H1)'但它不能按照我想要的方式工作,这会将最大列num_facturas增加1与$ currYear变量连接。

1 个答案:

答案 0 :(得分:3)

您需要先进行查询

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

然后您可以将结果连接到原始字符串。

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