【问题标题】:PDO LastInsertId returning nothingPDO LastInsertId 不返回任何内容
【发布时间】:2013-09-09 11:37:32
【问题描述】:

由于某种原因,我无法从我的 PDO 插入中获取 LastInsertId。我没有收到任何回复,如果我将它放在执行中,我会得到 -1,因为插入查询没有运行。但是,在执行抓取最后插入的 ID 之后,不会返回任何内容。

php 5.1.6
PECL pdo = 0.1.0

我查看了以下问题和许多其他堆栈交换问题。

  1. lastInsertId does not work in Postgresql
  2. PDO lastInsertId() returns 0
  3. PDO lastInsertId issues, php

但是,与 0 相比,没有返回任何内容。也没有记录错误。请参阅下面的代码。

连接

try {
  $conn = new PDO("pgsql:host=localhost port= dbname=", "", "");
  echo "PDO connection object created";
}
catch(PDOException $e) {
  echo $e->getMessage();
}

插入/返回最后一个 id

$stmt = $conn ->prepare("INSERT INTO sheet_tbl (site_id,  username, additionalvolunteers) VALUES(?,?,?)"); 
$stmt->bindParam(1,$site_id);
$stmt->bindParam(2,$username1);
$stmt->bindParam(3,$additionalvolunteers);
$site_id = $_POST['site_id'];   
$username1 = $user->name;
$additionalvolunteers = $_POST['additionalvolunteers'];
$stmt ->execute();
$newsheetID = $conn->lastInsertId('sheet_id');
echo $newsheetID . "last id"; 

【问题讨论】:

标签: pdo postgresql-9.2 lastinsertid


【解决方案1】:

你应该使用

$newsheetID = $conn->lastInsertId('sheet_id_**seq**');

只需在 id 后添加_seq

【讨论】:

    【解决方案2】:

    假设 sheet_id 类型为SERIAL,您可以使用LASTVAL()

    尝试(未测试,因为我没有 postgresql)

    $newsheetID = $conn->query("SELECT LASTVAL()");
    echo $newsheetID . "last id"; 
    

    【讨论】:

      【解决方案3】:

      我在 C# 中使用带有“返回行键”的 postgresql,它一直对我有用。
      我还在很多应用程序中使用 pdo/php。
      但是,我现在没有对服务器开放的 postgres 数据库进行测试。

      这应该可行,但未经测试。

      $site_id = $_POST['site_id'];   
      $username1 = $user->name;
      $additionalvolunteers = $_POST['additionalvolunteers'];
      
      $stmt = $conn ->prepare("INSERT INTO sheet_tbl (site_id,  username, additionalvolunteers) VALUES(:site_id, :username1, :additionalvolunteers) RETURNING row_id"); 
      
      $success = $stmt->execute([
          'site_id' => $site_id,
          'username1' => $username1,
          'additionalvolunteers' =>  $additionalvolunteers
      ]);
      // unsure about this
      $newsheetID =  $stmt->fetchColumn();
      echo $newsheetID . " last id"; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-18
        • 1970-01-01
        • 2012-07-31
        • 2022-12-19
        相关资源
        最近更新 更多