Guest User

Untitled

a guest
Mar 21st, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. <?php
  2. class DatabaseConnection {
  3. private $data, $sql, $conn, $host, $user, $pass, $dtbs;
  4.  
  5. public function __construct($host, $user, $pass, $dtbs) {
  6. $this->host = $host;
  7. $this->user = $user;
  8. $this->pass = $pass;
  9. $this->dtbs = $dtbs;
  10.  
  11. $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->dtbs);
  12. if ($this->conn) {
  13. return $this->conn;
  14. } else {
  15. return false;
  16. }
  17. }
  18.  
  19. public function query($sql, $data) {
  20. $this->data = $data;
  21. $this->sql = $sql;
  22. foreach ($data as $val) {
  23. if (strpos($this->sql, "'%i'") !== false || strpos($this->sql, "'%s'") !== false || strpos($this->sql, '"%i"') !== false || strpos($this->sql, '"%i"') !== false) {
  24. echo "SQL incorrect: There can't be any quotes around the parameters, because this function does that automaticly for you";
  25. exit();
  26. }
  27. $pos = strpos($this->sql, '%');
  28. $type = substr($this->sql, $pos, 2);
  29. if ($type == '%i') {
  30. if (is_int($val)) {
  31. $this->sql = substr_replace($this->sql, $val, $pos, 2);
  32. } else {
  33. echo "Parameter incorrect: Data is not an integer value";
  34. exit();
  35. }
  36. } elseif ($type == '%s') {
  37. if (!is_int($val)) {
  38. $this->sql = substr_replace($this->sql, "UNHEX('".bin2hex($val)."')", $pos, 2);
  39. } else {
  40. echo "Parameter incorrect: Data is an integer value";
  41. exit();
  42. }
  43. } else {
  44. echo "Parameter incorrect: Parameter %i for integer of %s for all other types of data";
  45. exit();
  46. }
  47. }
  48.  
  49. $this->query = $this->conn->query($this->sql);
  50. return $this->query;
  51.  
  52. }
  53.  
  54. public function fetch($query) {
  55. return $query->fetch_assoc();
  56. }
  57.  
  58. public function num_rows($query) {
  59. return $query->num_rows;
  60. }
  61.  
  62. }
  63. ?>
  64.  
  65. <?php
  66. function __autoload($class){
  67. require('classes/' . strtolower($class) . '.class.php');
  68. }
  69. require('config.php');
  70.  
  71. $sql = new DatabaseConnection(DB_HOST, DB_USER, DB_PASS, DB_DTBS);
  72. // The DB_xxxx constants are defined in config.php
  73. ?>
  74. <!doctype html>
  75. <html>
  76. <head>
  77. <meta charset="utf-8">
  78. <title>OOP - Object Orientated Programming</title>
  79. </head>
  80.  
  81. <body>
  82. <?php
  83. $data = array(1, "Brian o'Reilly");
  84. $query = $sql->query("SELECT * FROM users WHERE id = %i AND name = %s", $data);
  85. if ($sql->num_rows($query) > 0) {
  86. while ($r = $sql->fetch($query)) {
  87. echo '<p>User ' . $r['name'] . ' has ID ' . $r['id'] . '</p>';
  88. }
  89. } else {
  90. echo "<p>No results</p>";
  91. }
  92. ?>
  93. </body>
  94. </html>
Add Comment
Please, Sign In to add comment