Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2017
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. <?php
  2. /* Connect to a MySQL database using driver invocation */
  3. $dsn = 'mysql:dbname=database;host=mysql-local.app;port=3306';
  4. $user = 'user';
  5. $password = 'password';
  6.  
  7. try {
  8. $pdo = new PDO($dsn, $user, $password);
  9. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  10.  
  11. $result = $pdo->query("SHOW TABLES LIKE 'contact'");
  12. $table = $result->fetchAll();
  13. if (!count($table)) {
  14. $pdo->exec(
  15. "CREATE TABLE contact(\n" .
  16. " id INT AUTO_INCREMENT NOT NULL,\n" .
  17. " firstName VARCHAR(250) NOT NULL,\n" .
  18. " lastName VARCHAR(250) NOT NULL,\n" .
  19. " email VARCHAR(250) NOT NULL,\n" .
  20. " PRIMARY KEY (id)\n" .
  21. ")");
  22. }
  23.  
  24. $statement = $pdo->prepare("INSERT INTO contact (firstName, lastName, email) VALUES (:firstName, :lastName, :email)");
  25. $statement->bindParam(':firstName', $firstName);
  26. $statement->bindParam(':lastName', $lastName);
  27. $statement->bindParam(':email', $email);
  28.  
  29. // insert a row
  30. $firstName = "John";
  31. $lastName = "Doe";
  32. $email = "john@example.com";
  33. $statement->execute();
  34.  
  35. // insert another row
  36. $firstName = "Mary";
  37. $lastName = "Moe";
  38. $email = "mary@example.com";
  39. $statement->execute();
  40.  
  41. // insert another row
  42. $firstName = "Julie";
  43. $lastName = "Dooley";
  44. $email = "julie@example.com";
  45. $statement->execute();
  46.  
  47. echo '<pre>',
  48. json_encode(
  49. $pdo->query('SELECT id, firstName, lastName, email FROM contact')->fetchAll(PDO::FETCH_ASSOC),
  50. JSON_PRETTY_PRINT
  51. );
  52.  
  53. } catch (PDOException $e) {
  54. echo 'Connection failed: ' . $e->getMessage();
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement