简体   繁体   English

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

[英]How can I return LastInsertID from PDO whin a method of a class

I have create a small class that handles my MySql queries. 我创建了一个小类来处理MySql查询。

However, Now I am trying to get the value of the last inserted id but it is not wokring for me 但是,现在我正在尝试获取最后插入的id的值,但它对我来说不起作用

if my processQuery method in the class I do a prepare statement with any query like insert/update/remove 如果我在类中的processQuery方法我对任何查询(例如insert / update / remove)做一个prepare语句

I have added this line $this->lastInsertId = $this->pdo->lastInsertId; 我添加了这一行$ this-> lastInsertId = $ this-> pdo-> lastInsertId; which should give me the last inserted Id and stores it in the public variable called $lastInsertId then I can access it from my code outside. 这应该给我最后一个插入的ID并将其存储在名为$ lastInsertId的公共变量中,然后可以从外部代码访问它。

How can I get the last inserted ID to work with this class?? 我怎样才能获得最后插入的ID来使用该类?

Thanks 谢谢

this is my 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;

            }

    }

}

?>

You can add a method like this: 您可以添加如下方法:

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

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

It is just a wrapper around PDO::lastInsertId() . 它只是PDO::lastInsertId()的包装。 You won't need a local copy of the last insert id. 您将不需要最后一个插入ID的本地副本。 If PDO isn't connected it will throw an Exception. 如果未连接PDO,将抛出异常。 You can change this to return FALSE; 您可以更改它以return FALSE; if this fit's your design more. 如果这更适合您的设计。

Use it like this: 像这样使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM