TableMan
TableMan

Reputation: 205

PHP : return last inserted Id on statement

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:)

Upvotes: 0

Views: 156

Answers (5)

Justin
Justin

Reputation: 332

In your method code instead of using $inserted_id use a $_SESSION variable $_SESSION['inserted_id']. Now you will be able to use this in your index.php

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

Upvotes: 0

JuanSedano
JuanSedano

Reputation: 1025

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

});

Upvotes: 1

WagnerGTA
WagnerGTA

Reputation: 31

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!

Upvotes: 0

TecBrat
TecBrat

Reputation: 3719

The way I read that, your // Check for successful insertion section will never run because the function is terminated with return $result; before the conditional. Therefore, USER_CARD_INSERTED_SUCCESSFULLY is never returned.

Upvotes: 0

Machavity
Machavity

Reputation: 31614

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. So you can't get the ID of what hasn't been inserted yet.

$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). Consider making a class variable like $this->inserted_id and making a function that would return that value.

Upvotes: 2

Related Questions