2013-04-01 3 views
1

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; 

      } 

    } 

} 

?> 
+0

를 유를 사용하는 경우, u는 다시 클래스를 재 초기화하는 수 있습니다? 그렇지 않다면 디버깅을 시도하여 (lastInstertedId) 값이 올바르게 설정되었는지 확인하십시오 (echo 문). –

답변

2

입니다 :

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(); 
+0

Super, 그 트릭을 :) :)하지만 왜 당신이 매개 변수로 $ 이름 = NULL을 넣어 궁금해? 이것이 어디에서 작용할 수 있습니까? – Jaylen

+0

['lastInsertID'] (http://php.net/manual/en/pdo.lastinsertid.php)에서. 예를 들어 거기에있는 노트를 읽으면, PostgreSQL은 시퀀스 오브젝트가되기 위해'$ name' 매개 변수를 요구합니다. – Jon

+0

@Mike. 내가 말했듯이 이것은'PDO :: lastInsertId()'주위의 래퍼 일뿐입니다. 내가 링크 한 문서를 확인하고 Jon의 주석을 기록하십시오. – hek2mgl

관련 문제