<?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;
}
?>
I use a wrapper to call database queries, this has always worked well.
Except for today when I need to get the last insert ID. The error is "Undefined variable pdo"
I see why there is an error message, but not sure what is the solution while at the same time keeping the wrapper function?