選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

db.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. class DBHandler{
  3. private $mysql;
  4. function __construct($hostname, $username, $password, $database){
  5. global $dbs;
  6. $this->mysql = mysqli_connect($hostname, $username, $password);
  7. if(!$this->mysql) die("MySql error: " . mysql_error());
  8. mysqli_select_db($this->mysql, $database);
  9. }
  10. public function sanitize($text){
  11. return mysqli_real_escape_string($this->mysql, $text);
  12. }
  13. public function query($query){
  14. return mysqli_query($this->mysql, $query);
  15. }
  16. public function fetchRow($query){
  17. $result = $this->query($query);
  18. if($result === false || $result === true) die(mysqli_error($this->mysql));//return $result;
  19. return mysqli_fetch_assoc($result);
  20. }
  21. public function fetchAssoc($query){
  22. $result = $this->query($query);
  23. if($result === false || $result === true) die(mysqli_error($this->mysql));//return $result;
  24. $data = array();
  25. while($row = mysqli_fetch_assoc($result)){
  26. $data[] = $row;
  27. }
  28. return $data;
  29. }
  30. public function getError() {
  31. return mysqli_error($this->mysql);
  32. }
  33. public function lastInsertId(){
  34. return mysqli_insert_id($this->mysql);
  35. }
  36. public function getAffectedRows() {
  37. return mysqli_affected_rows($this->mysql);
  38. }
  39. public function verifyInteger($input, $minimum = 1){
  40. /*
  41. * Pretty hacky solution.
  42. *
  43. * First checks if the integer cast of the input is equal to itself.
  44. * This filters out decimals, alternate bases, and exponents.
  45. * Then checks if the input is numeric, which filters out other strings that slip by the first check.
  46. * This guarantees that it's in a numeric format, which combined with the first filter, should guarantee that it is an integer
  47. */
  48. return (((int) $input == $input) && is_numeric($input) && (($minimum === false) || (int) $input >= $minimum));
  49. }
  50. // Always returns a key of length 40. TODO: Add arbitrary length
  51. public function randomKey(){
  52. //Cryptographically Secure Key
  53. if(function_exists('openssl_random_pseudo_bytes')) return base64_encode(openssl_random_pseudo_bytes(30));
  54. //Fallback (Not cryptographically secure)
  55. $str = "";
  56. for($i=0; $i<30; $i++){
  57. $str .= chr(mt_rand(0,255));
  58. }
  59. return base64_encode($str);
  60. }
  61. }
  62. $db = new DBHandler('localhost', '2022mfelection', '<password>', '2022mfelection');