Guest User

Untitled

a guest
Dec 8th, 2017
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.16 KB | None | 0 0
  1. # Basic CRUD operations with PDO
  2.  
  3. CRUD = Create, Read, Update, Delete
  4.  
  5. ## Open a database connection
  6.  
  7. ```php
  8. $host = '127.0.0.1';
  9. $dbname = 'test';
  10. $username = 'root';
  11. $password = '';
  12. $charset = 'utf8';
  13. $collate = 'utf8_unicode_ci';
  14. $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
  15. $options = [
  16. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  17. PDO::ATTR_PERSISTENT => false,
  18. PDO::ATTR_EMULATE_PREPARES => false,
  19. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  20. PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset COLLATE $collate"
  21. ];
  22.  
  23. $pdo = new PDO($dsn, $username, $password, $options);
  24. ```
  25.  
  26. ## Select a single row
  27.  
  28. ```php
  29. $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND status=:status LIMIT 1");
  30. $stmt->execute(['email' => $email, 'status' => $status]);
  31. $user = $stmt->fetch();
  32. ```
  33.  
  34. ## Select multiple rows
  35.  
  36. With fetch for large results.
  37.  
  38. ```php
  39. $stmt = $pdo->prepare("SELECT * FROM employees WHERE name = :name");
  40. $stmt->execute(['name' => $name]);
  41.  
  42. foreach ($stmt as $row) {
  43. // do something with $row
  44. }
  45. ```
  46.  
  47. With fetchAll for small results.
  48.  
  49. ```php
  50. $news = $pdo->query('SELECT * FROM news')->fetchAll();
  51. ```
  52.  
  53. ## Insert a single row
  54.  
  55. ```php
  56. $row = [
  57. 'username' => 'bob',
  58. 'email' => 'bob@example.com'
  59. ];
  60. $sql = "INSERT INTO users SET username=:username, email=:email;";
  61. $status = $pdo->prepare($sql)->execute($row);
  62.  
  63. if ($status) {
  64. $lastId = $pdo->lastInsertId();
  65. echo $lastId;
  66. }
  67. ```
  68.  
  69. ## Insert multiple rows
  70.  
  71. ```php
  72. $rows = [];
  73. $rows[] = [
  74. 'username' => 'bob',
  75. 'email' => 'bob@example.com'
  76. ];
  77. $rows[] = [
  78. 'username' => 'max',
  79. 'email' => 'max@example.com'
  80. ];
  81.  
  82. $sql = "INSERT INTO users SET username=:username, email=:email;";
  83. $stmt = $pdo->prepare($sql);
  84. foreach ($rows as $row) {
  85. $stmt->execute($row);
  86. }
  87. ```
  88.  
  89. ## Update a single row
  90.  
  91. ```php
  92. $row = [
  93. 'id' => 1,
  94. 'username' => 'bob',
  95. 'email' => 'bob2@example.com'
  96. ];
  97. $sql = "UPDATE users SET username=:username, email=:email WHERE id=:id;";
  98. $status = $pdo->prepare($sql)->execute($row);
  99. ```
  100.  
  101. ## Update multiple rows
  102.  
  103. ```php
  104. $row = [
  105. 'updated_at' => '2017-01-01 00:00:00'
  106. ];
  107. $sql = "UPDATE users SET updated_at=:updated_at";
  108. $pdo->prepare($sql)->execute($row);
  109.  
  110. $affected = $pdo->rowCount();
  111. ```
  112.  
  113. ## Delete a single row
  114.  
  115. ```php
  116. $where = ['id' => 1];
  117. $pdo->prepare("DELETE FROM users WHERE id=:id")->execute($where);
  118. ```
  119.  
  120. ## Delete multiple rows
  121.  
  122. ```php
  123. $pdo->prepare("DELETE FROM users")->execute();
  124. ```
  125.  
  126. ## PDO datatypes
  127.  
  128. Getting dynamic (POST) data with null values can be difficult to handle with PDO.
  129. Here is a helper function to detect the correct data type.
  130.  
  131. ```php
  132. function get_pdo_type($value)
  133. {
  134. switch (true) {
  135. case is_bool($value):
  136. $dataType = PDO::PARAM_BOOL;
  137. break;
  138. case is_int($value):
  139. $dataType = PDO::PARAM_INT;
  140. break;
  141. case is_null($value):
  142. $dataType = PDO::PARAM_NULL;
  143. break;
  144. default:
  145. $dataType = PDO::PARAM_STR;
  146. }
  147. return $dataType;
  148. }
  149.  
  150. // Usage
  151. $email = $_POST['email'];
  152.  
  153. $pdo = new PDO('dsn', 'username', 'password');
  154. $sql = 'INSERT INTO users SET email=:email;';
  155. $stmt = $pdo->prepare($sql);
  156. $stmt->bindValue(':email', $email, get_pdo_type($email));
  157. $stmt->execute();
  158. ```
  159.  
  160. ## Prepared statements using the IN clause
  161.  
  162. It cannot be done with PDO, according to the PHP Manual's entry on PDO::prepare(), which says:
  163. "You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement."
  164.  
  165. This PDO helper function converts all array values into a (safe) quoted string.
  166.  
  167. ```php
  168. function quote_values(PDO $pdo, array $values) {
  169. array_walk($values, function (&$value) use ($pdo) {
  170. if($value === null) {
  171. $value = 'NULL';
  172. return;
  173. }
  174. $value = $pdo->quote($value);
  175. });
  176. return implode(',', $values);
  177. }
  178. ```
  179.  
  180. Example usage:
  181.  
  182. ```php
  183. $ids = [
  184. 1,
  185. 2,
  186. 3,
  187. "'",
  188. null,
  189. 'string',
  190. 123.456
  191. ];
  192.  
  193. $sql = sprintf("SELECT id FROM users WHERE id IN(%s)", quote_values($pdo, $ids));
  194. echo $sql . "\n";
  195.  
  196. $stmt = $pdo->prepare($sql);
  197. $stmt->execute();
  198. ```
  199.  
  200. Generated SQL:
  201.  
  202. ```sql
  203. SELECT id FROM users WHERE id IN('1','2','3','\'',NULL,'string','123.456')
  204. ```
Add Comment
Please, Sign In to add comment