2017-08-15 56 views
0

有沒有什麼辦法可以將mysql變量與mysql函數結果連接到一個insert語句中?如何連接PHP變量與mysql函數導致INSERT語句

我有下面的代碼: 「$ currYear」

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

我想連接與SELECT(MAX)功能,我已經試過」的$ currYear變量(SELECT MAX(h1.num_factura )+1 FROM facturas h1)',但它並不按我想要的方式工作,它將max列num_facturas遞增1,並與$ currYear變量連接。

回答

3

你需要讓查詢第一

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

,然後您可以連接結果到你的原始字符串。

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