gpt4 book ai didi

PHP : return last inserted Id on statement

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:12 26 4
gpt4 key购买 nike

所以我想从查询中获取并返回最后插入的 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"] 上,但我不知道该怎么做。

有什么想法吗?

谢谢:)

最佳答案

我认为你的陈述倒退了

$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 的类变量,并创建一个返回该值的函数。

关于PHP : return last inserted Id on statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27990262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com