簡體   English   中英

MySQL存儲過程沒有返回插入ID?

[英]MySQL stored procedure no insert ID returned?

我有一個非常簡單的查詢,不知道我在這里做錯了什么。

我的DB調用沒有像我期望的那樣接收insert id

表:

在此輸入圖像描述

存儲過程:

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 數據很好,但是$customerProductID返回0

select語句中的插入是否會返回insert ID

更新@Ravi-

在此輸入圖像描述

更新2:

我創建了一個單獨的方法,並對發送的查詢和數據進行了硬編碼。

它添加記錄很好,AI上升, 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:

從我做過的一些研究中,除非你使用mysqli方法,如$this->db->insert() ,否則它不會向你提供最后一個插入ID。

我將嘗試找出Ravi的建議,但似乎代碼點火器不允許顯示的示例。 至少我現在知道我並不瘋狂,除非你使用``insert`方法和存儲過程,否則它不是正常的行為。

這個答案可以解釋為什么您現有的代碼不起作用。 報價:

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(); 存儲過程調用之前和之后,以確保事務已提交。

理想情況下,以下行應該有效

$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();

為什么

insert_id()僅適用於Query BuilderQueries SP用於調用$this->db->query()但它不會返回數據insert_id()


怎么樣

在SP結束之前添加SELECT MAX(id) FROM order_customer_product; 因此,這將返回代碼的最后一個ID。


建議

我看到有一個對DB的插入查詢。 如果我使用類似的情況將使用普通的查詢生成器或/並將使用Codeigniter事務(我的另一個問題的答案)扭曲它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM