MySQL存储过程没有返回插入ID?

时间:2018-01-14 07:07:30

标签: php mysql codeigniter

我有一个非常简单的查询,不知道我在这里做错了什么。

我的数据库通话没有像我预期的那样收到insert id

表格

enter image description here

存储过程:

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(IN in_customerID INT, in_productID INT)
BEGIN
    INSERT INTO order_customer_product (customerID, productID, retailAmountAtPurchase, faceValue)
    SELECT
        in_customerID,
        in_productID,
        p.retail,
        p.faceValue
    FROM
        products as p
    WHERE 
        p.productID = in_productID;
END

PHP:

   public function addProduct($data, $userID)
    {
        // Do we already have a pending order for this user?
        $orderID = $this->doesOrderExist($userID);

        // We had no order, lets create one
        if (!$orderID) {
            $orderID = $this->createOrder($userID);
        }

        /**
         * Insert the customer product.
         * This relates a denomination to a customer.
         */
        $customerProductID = $this->addCustomerProduct($data);

        // Add this customer product to the order
        $this->addProductToOrder(array("customerProductID" => $customerProductID, "orderID" => $orderID));

        // Return
        return $customerProductID;
    }

    /**
     * Description: Add a customer product / reward
     * Page: client/add_reward
     */
    public function addCustomerProduct($data){
        $procedure = "CALL addCustomerProduct(?,?)";
        $result = $this->db->query($procedure, $data);
        return $this->db->insert_id();
    }

问题的关键是:$customerProductID = $this->addCustomerProduct($data);

正在将新记录插入表中,表格中有PK/AI。数据很好,但0将返回$customerProductID

select语句中的插入是否会返回insert ID

更新@Ravi -

enter image description here

更新2:

我创建了一个单独的方法,并对发送的查询和数据进行了硬编码。

它增加了记录,人工智能上升,0作为last id返回。

public function test(){
    $procedure = "CALL addCustomerProduct(?,?)";
    $result = $this->db->query($procedure, array("customerID" => 1, "productID" => 20));
    echo $this->db->insert_id();
}

还重新启动了MySQL服务器,以确保那里没有任何奇怪的事情。

此外,更新SP只是将随机数据插入表中而不使用选择。

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(IN in_customerID INT, in_productID INT)
BEGIN
    INSERT INTO order_customer_product (customerID, productID, retailAmountAtPurchase, faceValue)
    VALUES(8,2,'4.55',25);
END

更新3:

在插入之后,我打印出最后一个运行的查询以及结果。您会注意到有1个受影响的行(插入正在发生)但insert_id仍为0。

CALL addCustomerProduct('8','33')

CI_DB_mysqli_result Object
(
    [conn_id] => mysqli Object
        (
            [affected_rows] => 1
            [client_info] => mysqlnd 5.0.12-dev - 20150407 - $Id: b396954eeb2d1d9ed7902b8bae237b287f21ad9e $
            [client_version] => 50012
            [connect_errno] => 0
            [connect_error] => 
            [errno] => 0
            [error] => 
            [error_list] => Array
                (
                )

            [field_count] => 0
            [host_info] => Localhost via UNIX socket
            [info] => 
            [insert_id] => 0
            [server_info] => 5.6.35
            [server_version] => 50635
            [stat] => Uptime: 1637  Threads: 3  Questions: 508  Slow queries: 0  Opens: 113  Flush tables: 1  Open tables: 106  Queries per second avg: 0.310
            [sqlstate] => 00000
            [protocol_version] => 10
            [thread_id] => 25
            [warning_count] => 0
        )

    [result_id] => 1
    [result_array] => Array
        (
        )

    [result_object] => Array
        (
        )

    [custom_result_object] => Array
        (
        )

    [current_row] => 0
    [num_rows] => 
    [row_data] => 
)

更新4:

根据我所做的一些研究,除非您使用$this->db->insert()之类的mysqli方法,否则它不会向您提供最后一个插入ID。

我将尝试找出Ravi的建议,但似乎代码点火器不允许显示的示例。至少我现在知道我并不疯狂,除非你使用``insert`方法和存储过程,否则它不是正常的行为。

3 个答案:

答案 0 :(得分:5)

This answer可以解释为什么您现有的代码不起作用。引用:

  

CodeIgniter的insert_id()只会返回insert()的ID。   除非在调用函数之前执行$this->db->insert('table', $data);之类的操作,否则它将无法返回ID。

MySQL的LAST_INSERT_ID();应该在这里帮助你(假设你有权改变存储过程定义)。将其更改为:

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(
    IN in_customerID INT, in_productID INT, OUT out_customerProductID INT)
BEGIN
    INSERT INTO order_customer_product (
        customerID, productID, retailAmountAtPurchase, faceValue)
    VALUES(8,2,'4.55',25);

    SELECT LAST_INSERT_ID() INTO out_customerProductID;
END

然后使用以下内容获取输出参数值:

public function addCustomerProduct($data) {
    $procedure = "CALL addCustomerProduct("
                   . $this->db->escape($data["customerID"]).", "
                   . $this->db->escape($data["productID"]).", "
                   . "@customerProductID);"
    $this->db->query($procedure);
    $query = $this->db->query("SELECT @customerProductID AS customerProductID");
    if($query->num_rows() > 0)
      return $query->result()->customerProductID;
    else
      return NULL;
}

如果上述操作无效,请尝试在存储过程调用之前和之后添加$this->db->trans_start();$this->db->trans_complete();,以确保事务已提交。

答案 1 :(得分:3)

理想情况下,以下行应该有效

$this->db->insert_id;

但是,我不确定为什么不起作用,所以我建议采用以下解决方法,使用附加参数out_lastId重新编译您的过程,该参数将返回最后插入的ID

CREATE DEFINER=`root`@`localhost` PROCEDURE `addCustomerProduct`(IN in_customerID INT, in_productID INT, OUT out_lastId INT)

并且,在插入后设置最后插入id的值。

 SET out_lastId = LAST_INSERT_ID();

<强> ==更新==

$this->db->multi_query( "CALL addCustomerProduct($data, @id);SELECT @id as id" );
$db->next_result();            // flush the null RS from the call
$rs=$this->db->store_result();       // get the RS containing the id
echo $rs->fetch_object()->id, "\n";
$rs->free();

答案 2 :(得分:1)

<强>为什么

insert_id()仅适用于 Query Builder Queries SP用于与$this->db->query()通话,但不会返回数据insert_id()

如何

在SP结束之前添加SELECT MAX(id) FROM order_customer_product;。因此,这会将最后一个ID返回给您的代码。

建议

我看到有一个对DB的插入查询。如果我使用类似的案例,则会使用正常的 Query Builder 或/并将其与 Codeigniter Transactions(My answer on another question) 进行扭曲。

相关问题