gpt4 book ai didi

php - fatal error :调用未定义的方法 PDOStatement::lastInsertId()

转载 作者:行者123 更新时间:2023-11-29 06:12:28 25 4
gpt4 key购买 nike

我已经为 PDO 连接创建了一个数据库类。插入记录并在收到此错误“ fatal error :调用未定义的方法 PDOStatement::lastInsertId()”之后尝试获取最后插入 ID。

数据库类:

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

提前致谢。

最佳答案

对象应该是 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();

关于php - fatal error :调用未定义的方法 PDOStatement::lastInsertId(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37583980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com