简体   繁体   English

PHP:返回最后插入的ID on语句

[英]PHP : return last inserted Id on statement

So I want to get and return last inserted id from query. 所以我想获取并返回查询中最后插入的ID。 I am successfully get the last inserted id but I have a little problem when try to return it to index.php file 我成功获取了最后插入的ID,但是尝试将其返回到index.php文件时遇到了一些问题

This is my method code : 这是我的方法代码:

        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;
            }
        }

and this is my index.php file 这是我的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);
            } 

});

as you see, I want to put the last inserted id on $response["last_inserted_id"] , but I do not know how to do it. 如您所见,我想将最后插入的id放在$response["last_inserted_id"] ,但是我不知道该怎么做。

any ideas ? 有任何想法吗 ?

thanks:) 谢谢:)

I think you have your statements backwards 我想你的陈述倒退了

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

In prepared statements, execute is what runs your SQL. 在准备好的语句中, execute是运行SQL的内容。 So you can't get the ID of what hasn't been inserted yet. 因此,您无法获取尚未插入的内容的ID。

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

You're also not storing the data anywhere usable ( $inserted_id is a local variable to your function). 您也不会将数据存储在任何可用的位置( $inserted_id是函数的局部变量)。 Consider making a class variable like $this->inserted_id and making a function that would return that value. 考虑制作一个像$this->inserted_id这样的类变量,并制作一个将返回该值的函数。

Try this in you method: 在您的方法中尝试以下方法:

    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;
        }
    }

and in you index.php: 并在您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);
            } 

});

In your method code instead of using $inserted_id use a $_SESSION variable $_SESSION['inserted_id']. 在您的方法代码中,而不是使用$inserted_id使用$_SESSION变量$ _SESSION ['inserted_id']。 Now you will be able to use this in your index.php 现在您将可以在index.php中使用它

$response["last_inserted_id"] = $_SESSION['inserted_id '];  

The way I read that, your // Check for successful insertion section will never run because the function is terminated with return $result; 按照我的理解,由于功能以return $result;终止, return $result; // Check for successful insertion将永远不会运行return $result; before the conditional. 有条件之前。 Therefore, USER_CARD_INSERTED_SUCCESSFULLY is never returned. 因此,永远不会返回USER_CARD_INSERTED_SUCCESSFULLY。

In my functions, I usually return an array, for example: 在我的函数中,通常返回一个数组,例如:

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

and, in the main: 并且,主要是:

 $result = my_function();

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

I hope this help you! 希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM