Guest User

Untitled

a guest
Nov 23rd, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. <?php
  2. // ()
  3. // initialize base variables for PDO connection
  4. $host = 'localhost';
  5. $user = 'root';
  6. $password = 'bobi1996';
  7. $dbname = 'pdolab';
  8.  
  9. // initialize DSN
  10. $dsn = 'mysql:host=' . $host . ';dbname=' . $dbname;
  11.  
  12. // initialize PDO connection
  13. $pdo = new PDO($dsn, $user, $password);
  14.  
  15. // get all posts
  16. $sql = 'SELECT * FROM posts';
  17. $statement = $pdo->prepare($sql);
  18. $statement->execute([]);
  19. $posts = $statement->fetchAll(PDO::FETCH_ASSOC);
  20.  
  21. foreach ($posts as $post) {
  22. echo $post['title'] . '<br>';
  23. }
  24.  
  25. // get all posts from an inputted author
  26. $author = "John Doe";
  27. $sql = 'SELECT * FROM posts WHERE author = :author';
  28. $statement = $pdo->prepare($sql);
  29. $statement->execute(['author' => $author]);
  30. $posts = $statement->fetchAll(PDO::FETCH_ASSOC);
  31.  
  32. foreach ($posts as $post) {
  33. echo $post['title'] . '<br>';
  34. }
  35.  
  36. // insert a post
  37. $title = "Python & AI";
  38. $code = "a4";
  39. $author = "Ana Sparrow";
  40. $sql = 'INSERT INTO posts(title, code, author) VALUES(:title, :code, :author)';
  41. $statement = $pdo->prepare($sql);
  42. $statement->execute(['title' => $title, 'code' => $code, 'author' => $author]);
  43. echo "Post with the title \"" . $title . "\" is added in the database!";
  44.  
  45. // search for posts
  46. $keyword = "%data%";
  47. $sql = 'SELECT * FROM posts WHERE title LIKE :keyword';
  48. $statement = $pdo->prepare($sql);
  49. $statement->execute(['keyword' => $keyword]);
  50. $posts = $statement->fetchAll();
  51. foreach ($posts as $post) {
  52. echo $post['title'] . '<br>';
  53. }
Add Comment
Please, Sign In to add comment