MySql 쿼리를 처리하는 작은 클래스를 만들었습니다. 그러나 클래스의 메서드를 사용하여 PDO에서 LastInsertID를 반환하는 방법
가, 지금은 마지막으로 삽입 된 ID 값을 얻기 위해 노력하고 있지만 내가클래스 내 processQuery 방법은 내가 삽입과 같은 어떤 쿼리 문을 준비 할 경우 것이 wokring하지 않습니다/업데이트/remove
$ this-> lastInsertId = $ this-> pdo-> lastInsertId;이 줄을 추가했습니다. 마지막 삽입 된 ID를 제공해야하며 $ lastInsertId라는 공용 변수에 저장합니다. 그런 다음 코드 외부에서 액세스 할 수 있습니다.
마지막으로 삽입 한 ID를이 클래스와 함께 사용하려면 어떻게해야합니까 ??
감사
이 당신은 다음과 같은 방법을 추가 할 수 있습니다 내 수업
<?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;
}
}
}
?>
를 유를 사용하는 경우, u는 다시 클래스를 재 초기화하는 수 있습니다? 그렇지 않다면 디버깅을 시도하여 (lastInstertedId) 값이 올바르게 설정되었는지 확인하십시오 (echo 문). –