Skip to content

Instantly share code, notes, and snippets.

@J2112O
Created October 3, 2020 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save J2112O/124695d27c4e24c866c7f0f903d1d216 to your computer and use it in GitHub Desktop.
Save J2112O/124695d27c4e24c866c7f0f903d1d216 to your computer and use it in GitHub Desktop.
<?php
try {
// connection information
$pdo = new PDO('mysql:host=localhost;dbname=some_db_name;charset=utf8', 'some_user_name', 'some_password');
$pdo - ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// begin a transaction
$pdo->beginTransaction();
// Assume the 'user input' values have been sanitized and validated.
$first_name = 'Josh';
$last_name = 'Otwell';
// prepare insert statement
$insert_sql = "INSERT INTO `user_details`(`first_name`, `last_name`)
VALUES(:first_name, :last_name)";
$insert_stmt = $pdo->prepare($insert_sql);
$insert_stmt->bindValue(':first_name', $first_name);
$insert_stmt->bindValue(':last_name', $last_name);
// try the insert, if something goes wrong, rollback.
if ($insert_stmt->execute() === FALSE) {
$pdo->rollback();
echo 'Unable to insert data';
} else {
$last_insert_id = $pdo->lastInsertId();
echo 'Last Insert ID: '.$last_insert_id;
$pdo->commit();
}
} catch (PDOException $e) {
echo 'Database Error '.$e->getMessage().' in '.$e->getFile().
': '.$e->getLine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment