php - 如何在 PHP 中使用 SQL 或 PDO 获取最后插入的 id?
问题描述
大家好,也许有人可以帮助我找到从我的数据库中获取最后插入的 ID 的方法......我仍在努力学习。
一定有错误,但我不知道在哪里:/
这是我的 php 代码。数据被发送到我的数据库并保存,但我不知道如何取回用户 ID。它是我的用户表中的主键,并在 mysql 数据库中设置为自动增量。
我希望有人知道如何提供帮助:D 谢谢
php代码:
**
<php
$host = 'localhost';
$name = 'datatry';
$user = 'datatry';
$passwort = 'data';
try{
$mysql = new PDO("mysql:host=localhost;dbname=datatry", "datatry", "hello");
}
catch(PDOException $e){
echo "SQL Error: ".$e->getMessage();
}
if(isset($_POST["submit"])){
echo"Your UserId";
$statement = $mysql ->prepare ('INSERT INTO User (Name, Street, Birthdate, Code, Email, Password) VALUES (:Name, :Street, :Birthdate, :code, :Email, :Password)');
$statement->bindParam("Name", $_POST["Name"]);
$statement->bindParam("Nachname", $_POST["Street"]);
$statement->bindParam("Geburtstag", $_POST["Birthdate"]);
$statement->bindParam("PLZ", $_POST["Code"]);
$statement->bindParam("Email", $_POST["Email"]);
$statement->bindParam("Passwort", $_POST["Password"]);
$id = $mysql ->lastInsertId();
$statement = $mysql->query("SELECT LAST_INSERT_ID()");
$lastId = ♡statement->fetchColumn();
$statement-> execute ();
if(!$statement){
print_r($mysql->errorInfo());
}
}
?>
**
解决方案
推荐阅读
- javascript - 维护实时 HTMLCollection 的性能成本是多少?
- android - 颤动AndroidManifest警告-当前最小值为1
- android - 在解析 XML 时,如何在 Android 中使用 XmlPullParser 正确处理命名空间?
- node.js - 如何使用 Node.js 读取大文件的一部分?
- javascript - 如何使用三个返回变量中的特定变量?
- ios - 情节提要中的 UILabel 使用 U+2028 字符将文本分隔到两行,在一台设备上呈现垃圾
- ruby-on-rails - 警告:已经在 config/routes.rb 中初始化了常量
- javascript - 如何删除x和y轴上的数字?
- spring-boot - 有没有办法在Springboot中调用没有@enableWebMvc的异常处理程序方法
- java - 如何在没有弹簧配置的情况下自动装配 SessionFactory