我的脚本获取一个包含人员详细信息的CSV文件,并使用"INSERT into表"将其输入到我的mySQL数据库表中。表的主键是它们的ID号,每次插入时ID号都会自动递增。
每次插入后,我都会用一些PHP在服务器上为它们创建一个目录。目录名是他们自动生成的mySQL ID号。
在将他们的详细信息插入数据库后,我如何获得他们自动生成的身份证号码,以便为每个人创建目录?
PDO:
$last_id = $db->fetchAll('SELECT LAST_INSERT_ID() as last_id');
$last_id = intval($last_id[0]['last_id']);
或
$lastId = $db->lastInsertId();
这里有一个完整的回滚示例:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");
try {
$dbh->beginTransaction();
$tmt->execute( array('user', 'user@example.com'));
$dbh->commit();
print $dbh->lastInsertId();
} catch(PDOExecption $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "</br>";
}
} catch( PDOExecption $e ) {
print "Error!: " . $e->getMessage() . "</br>";
}
?>
我们使用PDO与数据库通信,并知道最后一个id:$dbh->lastInsertId()
您可以使用mysqli_insert_id函数。
此处的文档。