Advertisement
hujuice

PDO basic example (not tested)

Jan 22nd, 2016
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.57 KB | None | 0 0
  1. <?php
  2. // Args
  3. $dsn = 'mysql:host=myHostname;dbname=myDbName';
  4. $username = 'some_username';
  5. $password = 'some_password';
  6.  
  7. // Database, as PDO object
  8. $db = new \PDO($dsn, $username, $password);
  9.  
  10.  
  11. // SELECT example
  12. // =============================
  13. // A SELECT query
  14. $sql = 'SELECT name, email FROM users WHERE id = :id';
  15.  
  16. // Prepare the query
  17. $statement = $db->prepare($sql);
  18. $statement->bindValue(':id', (integer) $_GET['id'], \PDO::PARAM_INT);
  19.  
  20. // Run
  21. $statement->execute();
  22.  
  23. // Collect and return the user data, if present
  24. if ($result = $statement->fetch(\PDO::FETCH_ASSOC)) {
  25.     return $result;
  26. }
  27.  
  28.  
  29. // INSERT example
  30. // =============================
  31. // An INSERT query
  32. $sql = 'INSERT INTO users (name, email) VALUES (:name, :email)';
  33.  
  34. // Begin a transaction, to retrieve the last insert id
  35. $db->beginTransaction();
  36.  
  37. try {
  38.     // Prepare the query
  39.     $statement = $db->prepare($sql);
  40.     $statement->bindValue(':name', (string) $_POST['name'], \PDO::PARAM_STR);
  41.     $statement->bindValue(':email', (string) $_POST['email'], \PDO::PARAM_STR);
  42.  
  43.     // Run
  44.     $statement->execute();
  45.  
  46.     // Query to retrieve the last insert id
  47.     $sql = 'SELECT MAX(id) FROM users';
  48.  
  49.     // Prepare the query
  50.     $statement = $db->prepare($sql);
  51.  
  52.     // Run
  53.     $statement->execute();
  54.  
  55.     // Collect the data
  56.     $result = $statement->fetch(\PDO::FETCH_NUM));
  57.  
  58.     // Commit
  59.     $db->commit();
  60.  
  61.     // Last ID
  62.     $last_insert_id = $result[0];
  63. } catch (\PDOException $e) {
  64.     // Undo everything
  65.     $db->rollback();
  66.  
  67.     // Last ID
  68.     $last_insert_id = null;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement