database.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /*
  3. CREATE TABLE users
  4. (
  5. username varchar(50) PRIMARY KEY,
  6. password varchar(255),
  7. is_admin boolean default FALSE
  8. );
  9. */
  10. class user
  11. {
  12. public $username;
  13. public $admin;
  14. public function user($username, $admin)
  15. {
  16. $this->username = $username;
  17. $this->admin = $admin;
  18. }
  19. }
  20. class databank
  21. {
  22. private $connected = false;
  23. private $con;
  24. public function connect()
  25. {
  26. if(!$this->connected)
  27. {
  28. require_once('db_data.php');
  29. $this->con = new mysqli("localhost", "snuvi", $db_pass, "snuvi");
  30. if($this->con->connect_error)
  31. {
  32. echo "no databank connection";
  33. }
  34. else
  35. {
  36. $this->connected = true;
  37. }
  38. }
  39. }
  40. public function disconnect()
  41. {
  42. if($this->connected)
  43. {
  44. $this->con->close();
  45. $this->connected = false;
  46. }
  47. }
  48. public function isConnected()
  49. {
  50. return $this->connected;
  51. }
  52. public function getUser($username, $password)
  53. {
  54. $sql = $this->con->prepare("SELECT * FROM users WHERE username=?");
  55. if($sql == false)
  56. {
  57. echo $this->con->error;
  58. return null;
  59. }
  60. $sql->bind_param('s', $username);
  61. $sql->execute();
  62. $result = $sql->get_result();
  63. $sql->close();
  64. if($result->num_rows >= 1)
  65. {
  66. $r = $result->fetch_object();
  67. if(password_verify($password, $r->password))
  68. {
  69. $user = new user($r->username, $r->is_admin);
  70. return $user;
  71. }
  72. return null;
  73. }
  74. return null;
  75. }
  76. public function addUser($username, $password)
  77. {
  78. $hash = password_hash($password, PASSWORD_DEFAULT);
  79. $sql = $this->con->prepare("INSERT INTO users VALUES (?, ?, false);");
  80. $sql->bind_param('ss', $username, $hash);
  81. $sql->execute();
  82. if($sql->errno === 0)
  83. {
  84. $sql->close();
  85. return true;
  86. }
  87. if(substr($this->con->error, 0, 15) === "Duplicate entry")
  88. {
  89. echo "username already exists";
  90. }
  91. else
  92. {
  93. echo $this->con->error;
  94. echo "database error";
  95. }
  96. $sql->close();
  97. return false;
  98. }
  99. }
  100. ?>