Created
October 3, 2020 20:52
-
-
Save J2112O/124695d27c4e24c866c7f0f903d1d216 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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