Memorizzare l'ultimo id di un record mysql in una variabile.
Utilizzando PDO :
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'));
$last_id = $dbh->lastInsertId();
$dbh->commit();
print $dbh->lastInsertId(); ///ULTIMO ID INSERITO NEL DATABASE
} catch(PDOExecption $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "
";
}
} catch( PDOExecption $e ) {
print "Error!: " . $e->getMessage() . "
";
}
Utilizzando Mysqli:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tabella (nome, cognome, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id; //ULTIMO ID INSERITO IN DATABASE
echo "record inserito. L'ultimo id è: " . $last_id;
} else {
echo "Error: " . $sql . "
" . $conn->error;
}
Lascia un commento