我有一个INSERT语句和一个SELECT语句,我作为单个查询一起运行。第一个将几个参数插入发票'表(包括通过复杂的CONCAT_WS功能的增量发票编号,此处仅为了完整性而包括在内),而第二个返回新生成的发票编号:
LOCK TABLES invoices WRITE, invoices AS t2 READ, invoices AS t3 READ;
INSERT INTO invoices (project_id, billing_period, total_amount, created_date, invoice_number)
SELECT " . $_SESSION['project_id'] . ", '" . $_SESSION['invoice']['billing_period'] . "', " . $_SESSION['invoice']['overall_total'] . ", CURDATE(), CONCAT_WS(
'-', (YEAR(CURDATE())), (
IF (
YEAR(CURDATE())=SUBSTR(invoice_number FROM 1 FOR 4), LPAD(SUBSTR(invoice_number FROM 6 FOR 3)+1, 3, '0'), '001'
)
)
)
FROM invoices AS t2
ORDER BY t2.invoice_id DESC
LIMIT 1;
SELECT invoice_number
FROM invoices AS t3
WHERE t3.invoice_id=LAST_INSERT_ID();
UNLOCK TABLES;
如果我通过HTML表单和PHP脚本运行它,PHP会因以下错误而失败:
警告:mysqli_fetch_assoc()期望参数1为mysqli_result, 布尔值在...中给出。
该错误意味着查询返回FALSE(或TRUE?)。
但是如果我在phpMyAdmin或Querious中运行相同的查询(从Web上运行的查询的回显中复制/粘贴),它会成功并且非常清楚地按预期返回发票号。
我意识到我可以将它分成两个查询,并使用PHP的mysqli_insert_id()函数输入SELECT,但那里的乐趣在哪里?
编辑:@JayBlanchard,我已经看过"重复"它没有解决我的问题。来自@RiggsFolly的回复,虽然没有在之前的帖子中出现,但似乎已经解决了我的问题(尽管它引发了大量其他人的工作)