<?php
$sql = "insert into user (firstname, lastname) values (:firstname, :lastname)";
$arg = array("John", "Doe");
$stmt = pdo($sql, $arg);
$id = $pdo->lastInsertId();
print $id;
function pdo($sql, $args = NULL){
$dsn = "mysql:host=localhost;dbname=db;charset=utf8mb4";
try {
$pdo = new \PDO($dsn, "user", "123");
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
if (!$args){
return $pdo->query($sql);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
?>我使用包装器来调用数据库查询,这一直都很有效。
除了今天我需要获取最后一个插入ID,错误是"Undefined variable pdo“
我明白了为什么会有错误消息,但不确定在保留包装器函数的同时解决方案是什么?
发布于 2019-07-07 07:23:23
您可能只想让一个函数创建DB连接,并让应用程序代码直接使用PDO。这将比试图包装PDO的所有功能更简单。这样做会变得很复杂。
如果您确实需要PDO连接的包装器,那么您可能希望创建一个具有在同一连接上操作的不同方法的类。该类可以有一个特殊的insert方法来返回插入的ID,以及一个fetch方法来检索结果。
https://stackoverflow.com/questions/56918255
复制相似问题