使用最后插入的id来插入查询

时间:2017-04-18 11:09:42

标签: php mysql

我有这样的查询:

<?php   
$this->db->query("INSERT INTO customer SET email = '" . $this->db->escape($data['email']) . "'");
?>

在此之后,我需要对另一个表进行INSERT:

$this->db->query("INSERT INTO order SET customer_id = '" . //here goes the id i need from previous query ."'";

在我的客户表中,我只有一个名为customer_id的自动增量列,在第一次插入此表后,我需要获取此customer_id值并将其用于下一次插入(订购表)。

我该怎么做?我读到了

$mysqli->insert_id

但是所有示例都连接到数据库,而我已经连接到数据库并使用this-&gt; db运行查询。任何有关语法或其他解决方案的帮助都非常感谢!

3 个答案:

答案 0 :(得分:1)

使用以下代码,您可以获得最后插入的ID,因此您需要在第一次插入后和第二次插入之前使用它。

$insert_id = $this->db->insert_id();

一个例子是:

<?php   
$this->db->query("INSERT INTO customer (email) values ('".$this->db->escape($data['email']."')";
$insert_id = $this->db->insert_id();
$this->db->query("INSERT INTO `order` (customer_id) values ({$insert_id})";
?>

$ insert_id是一个整数,所以你不需要再次转义它。 虽然订单是保留字,但您可能想要更改表名。

答案 1 :(得分:0)

您将获得最后一个插入ID,如下所示..

<?php
$this->db->query("INSERT INTO customer SET email = '" . $this->db->escape($data['email']) . "'");    
$id=$this->db->insert_id();
?>

通常,insert_id()函数返回自动递增的Mysql列中最后插入的id。 它大部分时间都可以工作,但对于那个不工作的实例,你很幸运能及时发现(就像我一样)

$this->db->insert(table_name, $data);
return $this->db->insert_id();

如果它发生故障,快速修复就会变成原始状态,如下所示:

$this->db->insert(table_name, $data);
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
return $row['LAST_INSERT_ID()'];

答案 2 :(得分:0)

实际上你的插入查询是错误的,所以在代码

下面使用
 <?php   
    $query = "INSERT INTO customer ( email ) VALUES ('" .$this->db->escape($data['email']) . "')";
    $this->db->query($query );
    $id=$this->db->insert_id();
    ?>
相关问题