【问题标题】:Getting data from new row从新行获取数据
【发布时间】:2015-10-08 07:27:24
【问题描述】:

我编写了在 MySql 表中插入新记录的代码。有什么方法可以让我在不进行新查询的情况下获得插入的行id

try {

    $NEWData = $DBH->prepare("
    INSERT INTO boge 
        (name, grade, school, made, type) 
        VALUES (:name, :grade, :school, NOW(), '2')"
    );

    $NEWData->bindParam(':name', $navn); // Erik
    $NEWData->bindParam(':grade', $skid); // 12
    $NEWData->bindParam(':school', $klasseId); // 1 - school have an id

    // wants to get the new rows id
    $NEWData->execute();


} catch(PDOException $e) {

    echo $e->getMessage();
    exit();

}

【问题讨论】:

标签: php mysql sql web pdo


【解决方案1】:

您可以使用 pdo 函数 lastInsertId http://php.net/manual/en/pdo.lastinsertid.php

此外,在某些数据库引擎中,您可以在 INSERT INTO 之后添加“返回 id”,但 PDO 方式将始终有效。

【讨论】:

  • 感谢您的帮助:-D
【解决方案2】:

试试这个:

$last_insert_id = $DBH->lastInsertId();
echo "<p>$last_insert_id</p>";

【讨论】:

  • 感谢您的帮助:-D
【解决方案3】:

对于高流量网站,使用 lastInsertId 可能会有一些小问题。 这是一个更有效的解决方案:

// wants to get the new rows id
$insert = $NEWData->execute();
$lastId = $insert->insertId();

这使您能够以最高精度获得正确的插入 ID。

【讨论】:

  • 对不起,我得到 500 错误然后我运行代码,它没有给我 PDO 错误
  • 我没有为任何东西编写代码。我刚刚纠正了一个人的错误。您可能需要提出一个新问题并在此处发布链接,以便我修复您的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-04
  • 1970-01-01
相关资源
最近更新 更多