Fatal error: Call to undefined method PDOStatement::lastInsertId()

被刻印的时光 ゝ 提交于 2021-02-04 21:16:06

问题


I have created a database class for PDO connection. Inserted record and tried to get last insert id after that getting this error "Fatal error: Call to undefined method PDOStatement::lastInsertId()".

Database class:

class Database {
public static $link = null ;

public static function getLink( ) {
    if ( self :: $link ) {
        return self :: $link ;
    }

    $ini = "config.ini" ;
    $parse = parse_ini_file ( $ini , true ) ;
    $driver = $parse [ "db_driver" ] ;
    $dsn = "${driver}:" ;
    $user = $parse [ "db_user" ] ;
    $password = $parse [ "db_password" ] ;
    $options = $parse [ "db_options" ] ;
    $attributes = $parse [ "db_attributes" ] ;

    foreach ( $parse [ "dsn" ] as $k => $v ) {
        $dsn .= "${k}=${v};" ;
    }

    self :: $link = new PDO ( $dsn, $user, $password, $options ) ;

    foreach ( $attributes as $k => $v ) {
        self :: $link -> setAttribute ( constant ( "PDO::{$k}" )
            , constant ( "PDO::{$v}" ) ) ;
    }

    return self :: $link ;
}

public static function __callStatic ( $name, $args ) {
    $callback = array ( self :: getLink ( ), $name ) ;
    return call_user_func_array ( $callback , $args ) ;
}

} configuration file config.ini

db_driver=mysql
db_user=username
db_password=password

[dsn]
host=hostname
port=3306
dbname=databasename

[db_options]
PDO::MYSQL_ATTR_INIT_COMMAND=set names utf8

[db_attributes]
ATTR_ERRMODE=ERRMODE_EXCEPTION
############

Code to insert query:

$pdo = Database::prepare("INSERT INTO customer (first_name, last_name, join_date) VALUES (?, ?, ?)");
$pdo->bindParam(1, $firstName);
$pdo->bindParam(2, $lastName);
$pdo->bindParam(3, $currentDate);
$pdo->execute();
$custId = $pdo->lastInsertId();
$pdo->closeCursor();

Thanks in advance.


回答1:


The Object should be PDO to get lastInsertId(). Correction in call bellow.

$pdo = Database::getLink();
$statement = $pdo->prepare("INSERT INTO customer (first_name, last_name, join_date) VALUES (?, ?, ?)");
$statement->bindParam(1, $firstName);
$statement->bindParam(2, $lastName);
$statement->bindParam(3, $currentDate);
$statement->execute();
$custId = $pdo->lastInsertId();
$statement->closeCursor();


来源:https://stackoverflow.com/questions/37583980/fatal-error-call-to-undefined-method-pdostatementlastinsertid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!