INSERT, UPDATE AND DELETE WITH PDO


SUBMITTED BY: Konstantinos

DATE: March 10, 2020, 8:34 p.m.

FORMAT: Text only

SIZE: 3.0 kB

HITS: 132302

  1. INSERT
  2. Assuming a HTML form of method $_POST with the appropriate fields in it, the following would insert a new record in a table called movies. Note that in a real world example all the variables from $_POST would be validated before been sent to the query.
  3. $sql = "INSERT INTO movies(filmName,
  4. filmDescription,
  5. filmImage,
  6. filmPrice,
  7. filmReview) VALUES (
  8. :filmName,
  9. :filmDescription,
  10. :filmImage,
  11. :filmPrice,
  12. :filmReview)";
  13. $stmt = $pdo->prepare($sql);
  14. $stmt->bindParam(':filmName', $_POST['filmName'], PDO::PARAM_STR);
  15. $stmt->bindParam(':filmDescription', $_POST['filmDescription'], PDO::PARAM_STR);
  16. $stmt->bindParam(':filmImage', $_POST['filmImage'], PDO::PARAM_STR);
  17. // use PARAM_STR although a number
  18. $stmt->bindParam(':filmPrice', $_POST['filmPrice'], PDO::PARAM_STR);
  19. $stmt->bindParam(':filmReview', $_POST['filmReview'], PDO::PARAM_STR);
  20. $stmt->execute();
  21. Notice the use of colons as position placeholder for the bindParam() methods.
  22. GETTING AUTO INCREMENT KEY VALUES WITH LASTINSERTID()
  23. When using SQL INSERT you may have set up your database table with an auto_increment field to ensure your primary keys remain unique. You may need to know what this value is as soon as the database creates it. In this scenario the PDO method lastInsertId() can be used. Create a variable from this property after the execute() method as follows:
  24. $stmt->execute();
  25. $newId = $pdo->lastInsertId();
  26. UPDATE
  27. An UPDATE example would work in the same fashion this time the SQL has a WHERE clause to identify which record to update.
  28. $sql = "UPDATE movies SET filmName = :filmName,
  29. filmDescription = :filmDescription,
  30. filmImage = :filmImage,
  31. filmPrice = :filmPrice,
  32. filmReview = :filmReview
  33. WHERE filmID = :filmID";
  34. $stmt = $pdo->prepare($sql);
  35. $stmt->bindParam(':filmName', $_POST['filmName'], PDO::PARAM_STR);
  36. $stmt->bindParam(':filmDescription', $_POST['$filmDescription'], PDO::PARAM_STR);
  37. $stmt->bindParam(':filmImage', $_POST['filmImage'], PDO::PARAM_STR);
  38. // use PARAM_STR although a number
  39. $stmt->bindParam(':filmPrice', $_POST['filmPrice'], PDO::PARAM_STR);
  40. $stmt->bindParam(':filmReview', $_POST['filmReview'], PDO::PARAM_STR);
  41. $stmt->bindParam(':filmID', $_POST['filmID'], PDO::PARAM_INT);
  42. $stmt->execute();
  43. DELETE
  44. Finally a DELETE statement. Like the UPDATE a WHERE clause ensures the correct record is removed.
  45. $sql = "DELETE FROM movies WHERE filmID = :filmID";
  46. $stmt = $pdo->prepare($sql);
  47. $stmt->bindParam(':filmID', $_POST['filmID'], PDO::PARAM_INT);
  48. $stmt->execute();
  49. That covers the basics of getting started with PDO.

comments powered by Disqus