如何在PHP PDO MySQL中获取lastInsertId后插入至关联表?
PHP PDO 关联表插入lastInsertId失败的修复方案
你代码里的核心错误是处理关联表插入时对lastInsertId的用法完全错误,直接拼接变量到SQL语句中,还错误执行了绑定操作,导致参数不匹配,最终无法正确插入关联数据。
错误点分析
- 插入
tbl_invoice_items的SQL语句中,直接将$lastserted_id硬编码进VALUES列表,同时错误执行了$this->db->bind("$lastserted_id", 'invoice_fk');——这完全搞反了参数名和绑定的值,不符合PDO参数绑定的规范。 - 表名拼写错误:
tbl_invoce_total应为tbl_invoice_total(单词invoice少写了一个i),虽不是当前问题直接原因,但会影响后续维护。
修正后的完整代码
public function addinvoice($data){ // 修正表名拼写错误 $this->db->query('INSERT INTO tbl_invoice_total (sub_total,total_tax,total,last_activity) VALUES (:sub_total,:total_tax,:total,:last_activity)'); $this->db->bind(':sub_total',$data['sub_total']); $this->db->bind(':total_tax',$data['total_tax']); $this->db->bind(':total',$data['total']); $this->db->bind(':last_activity',$data['last_activity']); $this->db->execute(); $lastserted_id = $this->db->lastInsertId(); echo $lastserted_id; foreach ($data['productname'] as $key => $value) { // 添加:invoice_fk占位符,替换直接拼接的变量 $this->db->query("INSERT INTO tbl_invoice_items (users_id,customer_id,companies_id,invoice_fk,productname,quantity,price,last_activity) VALUES (:users_id,:customer_id,:companies_id,:invoice_fk,:productname,:quantity,:price,:last_activity)"); $this->db->bind(':users_id',$data['users_id']); $this->db->bind(':customer_id',$data['customer_id']); $this->db->bind(':companies_id',$data['companies_id']); // 正确绑定:invoice_fk到获取到的lastInsertId $this->db->bind(':invoice_fk', $lastserted_id); $this->db->bind(':productname',$data['productname'][$key]); $this->db->bind(':quantity',$data['quantity'][$key]); $this->db->bind(':price',$data['price'][$key]); $this->db->bind(':last_activity',$data['last_activity']); $this->db->execute(); } echo $lastserted_id; die( print_r($data)); }
关键修改说明
- 给关联表插入的SQL语句添加
:invoice_fk占位符,遵循PDO参数绑定的规范,避免直接拼接变量带来的安全隐患和语法问题。 - 删除错误的
$this->db->bind("$lastserted_id", 'invoice_fk');,替换为正确的$this->db->bind(':invoice_fk', $lastserted_id);,将获取到的主表ID绑定到关联表的外键字段。 - 修正主表表名的拼写错误,避免后续出现表不存在的问题。
内容的提问来源于stack exchange,提问作者Kerub Angel
相关产品推荐
相关产品推荐

