gpt4 book ai didi

php - 如何从类的方法中从 PDO 返回 LastInsertID

转载 作者:行者123 更新时间:2023-11-29 06:50:29 26 4
gpt4 key购买 nike

我创建了一个小类来处理我的 MySql 查询。

但是,现在我试图获取最后插入的 id 的值,但它对我来说不起作用

如果我在类中使用 processQuery 方法,我会使用任何查询(如插入/更新/删除)执行准备语句

我添加了这一行 $this->lastInsertId = $this->pdo->lastInsertId;这应该给我最后插入的 Id 并将它存储在名为 $lastInsertId 的公共(public)变量中,然后我可以从我的外部代码访问它。

如何获取最后插入的 ID 以使用此类?

谢谢

这是我的类(class)

<?php

class connection {

private $connString;
private $userName;
private $passCode;
private $server;
private $pdo;
private $errorMessage;
public $lastInsertId;

private $pdo_opt = array (
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);


function __construct($dbName, $serverName = 'localhost'){

//sets credentials
$this->setConnectionCredentials($dbName, $serverName);

//start the connect
$this->startConnection();

}

function startConnection(){


$this->pdo = new PDO($this->connString, $this->userName, $this->passCode, $this->pdo_opt);

if( ! $this->pdo){

$this->errorMessage = 'Failed to connect to database. Please try to refresh this page in 1 minute. ';
$this->errorMessage .= 'However, if you continue to see this message please contact your system administrator.';


}

}


//this will close the PDO connection
public function endConnection(){

$this->pdo = null;
}

//return a dataset with the results
public function getDataSet($query, $data = NULL)
{
$cmd = $this->pdo->prepare( $query );

$cmd->execute($data);

return $cmd->fetchAll();
}


//return a dataset with the results
public function processQuery($query, $data = NULL)
{
$cmd = $this->pdo->prepare( $query );
$this->lastInsertId = $this->pdo->lastInsertId;
return $cmd->execute($data);
}


//this where you need to set new server credentials with a new case statment
function setConnectionCredentials($dbName, $serv){

switch($serv){

case 'BLAH':
$this->connString = 'mysql:host='.$serv.';dbname='.$dbName.';charset=utf8';
$this->userName = 'BLAH';
$this->passCode = 'BLAH';
break;

default:
$this->connString = 'mysql:host='.$serv.';dbname='.$dbName.';charset=utf8';
$this->userName = 'BLAH2';
$this->passCode = 'BLAH2';
break;

}

}

}

?>

最佳答案

你可以像这样添加一个方法:

public function lastInsertId($name = NULL) {
if(!$this->pdo) {
throw new Exception('not connected');
}

return $this->pdo->lastInsertId($name);
}

它只是PDO::lastInsertId() 的包装器.您不需要最后一个插入 ID 的本地副本。如果未连接 PDO,它将抛出异常。如果这更适合您的设计,您可以将其更改为 return FALSE;

像这样使用它:

$con = new connection('testdb'); 
$con->processQuery('INSERT INTO `foo` ....');
$lastInsertId = $con->lastInsertId();

关于php - 如何从类的方法中从 PDO 返回 LastInsertID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15753753/

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