PHP:在语句上返回最后插入的Id

时间:2015-01-16 18:16:45

标签: php mysql

所以我想从查询中获取并返回最后插入的id。 我成功获取最后一个插入的id但是在尝试将其返回到index.php文件时我有一点问题

这是我的方法代码:

        public function InsertUserCard(UserCard $uc)
        {
            if(!$this->DuplicateUserCard($uc))
            {
                $stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
                                             (user_id, card_id, barcode, barcode_format, created_at, updated_at) 
                                             VALUES(?, ?, ?, ?, ?, ?)");
                if ($stmt == FALSE)
                {
                    die($this->conn->error);
                }
                else  
                {
                    $user_id = NULL;
                    $card_id = NULL;
                    $barcode = NULL;
                    $barcode_format = NULL;
                    $created_at = NULL;
                    $updated_at = NULL;
                    $stmt->bind_param("iissss", $user_id, $card_id, $barcode, $barcode_format, $created_at, $updated_at);
                    $user_id = $uc->getUserId();
                    $card_id =  $uc->getCardId();
                    $barcode = $uc->getBarcode();
                    $barcode_format = $uc->getBarcodeFormat();
                    $created_at = $uc->getCreatedAt();
                    $updated_at = $uc->getUpdatedAt();

                    $stmt->execute();
                    $result = $this->conn->insert_id;   <-- This is how I get the last inserted id
                    $stmt->close();
                }

                // Check for successful insertion
                if ($result) 
                {
                    // User card successfully inserted
                    return USER_CARD_INSERTED_SUCCESSFULLY;
                } 
                else 
                {
                    // Failed to insert user card
                    return USER_CARD_INSERT_FAILED;
                }
            }
            else
            {
                return USER_CARD_ALREADY_EXISTED;
            }
        }

这是我的index.php文件

$app->post('/user/card/rev', 'authenticate', function() use ($app) 
{
            // check for required params
            verifyRequiredParams(array('user_id', 'card_id', 'barcode', 'barcode_format', 'created_at', 'updated_at'));

            global $user_id;

            $response = array();
            $timestamp = time();
            $now = date("Y-m-d H:i:s", $timestamp);
            $uc = new UserCard();
            $uc->setUserId($user_id);
            $uc->setCardId($app->request->post('card_id'));
            $uc->setBarcode($app->request->post('barcode'));
            $uc->setBarcodeFormat($app->request->post('barcode_format'));
            $uc->setCreatedAt($app->request->post('created_at'));
            $uc->setUpdatedAt($app->request->post('updated_at'));


            // choose card from db by user
            $UserCardDB = new UserCardDB(MySqlDb::getInstance()->connect());
            $UserCard = $UserCardDB->InsertUserCard($uc);

            if ($UserCard == USER_CARD_INSERTED_SUCCESSFULLY) 
            {
                $response["error"] = false;
                $response["message"] = "User Card added successfully";
                $response["current_timestamp"] = $timestamp;
                $response["current_date"] = $now;
                $response["last_inserted_id"] = SHOULD_BE_HERE;
                echoRespnse(201, $response);
            } 

});

如您所见,我想将最后插入的ID放在$response["last_inserted_id"]上,但我不知道该怎么做。

任何想法?

感谢:)

5 个答案:

答案 0 :(得分:2)

我认为你的陈述是向后的

$inserted_id = $this->conn->insert_id;
$result = $stmt->execute();

在准备好的语句中,execute是运行SQL的。因此,您无法获取尚未插入内容的ID。

$result = $stmt->execute();
$inserted_id = $this->conn->insert_id;

您还没有将数据存储在任何可用的位置($inserted_id是您的函数的局部变量)。考虑创建一个类变量,如$this->inserted_id,并创建一个返回该值的函数。

答案 1 :(得分:1)

在你的方法中试试这个:

    public function InsertUserCard(UserCard $uc)
    {
        if(!$this->DuplicateUserCard($uc))
        {
            $stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
                                         (user_id, card_id, barcode, barcode_format, created_at, updated_at) 
                                         VALUES(?, ?, ?, ?, ?, ?)");
            if ($stmt == FALSE)
            {
                die($this->conn->error);
            }
            else  
            {
                $user_id = NULL;
                $card_id = NULL;
                $barcode = NULL;
                $barcode_format = NULL;
                $created_at = NULL;
                $updated_at = NULL;
                $stmt->bind_param("iissss", $user_id, $card_id, $barcode, $barcode_format, $created_at, $updated_at);
                $user_id = $uc->getUserId();
                $card_id =  $uc->getCardId();
                $barcode = $uc->getBarcode();
                $barcode_format = $uc->getBarcodeFormat();
                $created_at = $uc->getCreatedAt();
                $updated_at = $uc->getUpdatedAt();
            }

            // Check for successful insertion
            if ($stmt->execute()) 
            {
                $result = $this->conn->insert_id;
                $stmt->close();
                return $result;
            } 
            else 
            {
                // Failed to insert user card
                return USER_CARD_INSERT_FAILED;
            }
        }
        else
        {
            return USER_CARD_ALREADY_EXISTED;
        }
    }

并在你的index.php:

$app->post('/user/card/rev', 'authenticate', function() use ($app) 
{
            // check for required params
            verifyRequiredParams(array('user_id', 'card_id', 'barcode', 'barcode_format', 'created_at', 'updated_at'));

            global $user_id;

            $response = array();
            $timestamp = time();
            $now = date("Y-m-d H:i:s", $timestamp);
            $uc = new UserCard();
            $uc->setUserId($user_id);
            $uc->setCardId($app->request->post('card_id'));
            $uc->setBarcode($app->request->post('barcode'));
            $uc->setBarcodeFormat($app->request->post('barcode_format'));
            $uc->setCreatedAt($app->request->post('created_at'));
            $uc->setUpdatedAt($app->request->post('updated_at'));


            // choose card from db by user
            $UserCardDB = new UserCardDB(MySqlDb::getInstance()->connect());
            $UserCard = $UserCardDB->InsertUserCard($uc);

            if (($UserCard != "USER_CARD_INSERT_FAILED") and ($UserCard != "USER_CARD_ALREADY_EXISTED"))
            {
                $response["error"] = false;
                $response["message"] = "User Card added successfully";
                $response["current_timestamp"] = $timestamp;
                $response["current_date"] = $now;
                $response["last_inserted_id"] = $UserCard;
                echoRespnse(201, $response);
            } 

});

答案 2 :(得分:0)

在您的方法代码中,而不是使用$inserted_id,请使用$_SESSION变量$ _SESSION [&#39; inserted_id&#39;]。现在,您可以在index.php

中使用它
$response["last_inserted_id"] = $_SESSION['inserted_id '];  

答案 3 :(得分:0)

我阅读的方式是,您的// Check for successful insertion部分永远不会运行,因为该函数在条件之前以return $result;终止。因此,永远不会返回USER_CARD_INSERTED_SUCCESSFULLY。

答案 4 :(得分:0)

在我的函数中,我通常返回一个数组,例如:

 $result = array( "status" => $status, "id" => $id );
 return $result;

,主要是:

 $result = my_function();

 $status = $result['status'];
 $id = $result['id'];

我希望这能帮到你!