douchui1488 2015-01-16 18:16
浏览 19
已采纳

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

So I want to get and return last inserted id from query. I am successfully get the last inserted id but I have a little problem when try to return it to index.php file

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

$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.

any ideas ?

thanks:)

  • 写回答

5条回答 默认 最新

  • dscc90150010 2015-01-16 18:31
    关注

    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:

    $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);
                } 
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?