Advertisement
voodooKobra

PHPDev post

Sep 3rd, 2014
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. [quote="Celauran"]First of all, stop using mysql_ functions. They've been worst practice for years, are deprecated, and will be removed from the language. That said, the easiest way to prevent SQL injection is to use prepared statements.[/quote]
  2.  
  3. Here's a class I like to use:
  4. [php]class DB extends PDO
  5. {
  6. /**
  7. * Parameterized Query
  8. *
  9. * @param string $statement
  10. * @param array $params
  11. * @param const $fetch_style
  12. * @return mixed -- array if SELECT
  13. */
  14. public function dbQuery($statement, $params = [], $fetch_style = PDO::FETCH_ASSOC)
  15. {
  16. if (empty($params)) {
  17. $stmt = $this->query($statement);
  18. if ($stmt !== false) {
  19. return $stmt->fetchAll($fetch_style);
  20. }
  21. return false;
  22. }
  23. $stmt = $this->prepare($statement);
  24. $exec = $stmt->execute($params);
  25. if ($exec) {
  26. return $stmt->fetchAll($fetch_style);
  27. }
  28. return false;
  29. }
  30.  
  31. /**
  32. * Fetch a single result -- useful for SELECT COUNT() queries
  33. *
  34. * @param string $statement
  35. * @param array $params
  36. * @return mixed
  37. */
  38. public function single($statement, $params = [])
  39. {
  40. $stmt = $this->prepare($statement);
  41. $exec = $stmt->execute($params);
  42. if ($exec) {
  43. return $stmt->fetchColumn(0);
  44. }
  45. return false;
  46. }
  47. }[/php]
  48.  
  49. Example time! Because everybody loves examples.
  50.  
  51. Old code:
  52. [php]<?php
  53. mysql_connect("localhost", "root", "hackme");
  54. mysql_select_db("mission_critical");
  55.  
  56. $sql = mysql_query("SELECT * FROM table WHERE id = '" . $_GET['id'] ."'");
  57. $data = mysql_fetch_assoc($sql);[/php]
  58.  
  59. New code:
  60. [php]<?php
  61. include "keep_this_out_of_document_root_please/DB.php";
  62. $mySQL = new DB("mysql:host=localhost;dbname=mission_critical", "root", "hackme");
  63. $data = $mySQL->dbQuery("SELECT * FROM table WHERE id = ?", array( $_GET['id'] ));[/php]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement