我为PDO连接创建了一个数据库类。插入记录并尝试在获得此错误后获取最后一个插入ID"致命错误:调用未定义的方法PDOStatement :: lastInsertId()"。
数据库类:
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 ) ;
}
} 配置文件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
############
插入查询的代码:
$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();
提前致谢。
答案 0 :(得分:2)
Object应为PDO以获取lastInsertId()。通话中的更正。
$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();