douti9253 2019-07-06 23:14
浏览 54

PHP如何在包装器中调用数据库时获取最后一个插入ID

<?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?

  • 写回答

1条回答 默认 最新

  • doupin8555 2019-07-06 23:23
    关注

    You might just want to have a function create the DB connection and let the application code use the PDO API directly. That would be simpler than trying to wrap all the functionality of the PDO API. It would get complicated to do that.

    If you really need a wrapper around your PDO connection, then you may want to create a class with different methods operating on the same connection. The class could have a special insert method that returns the inserted ID as well as a fetch method to retrieve results.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集