Guest User

Untitled

a guest
Dec 15th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. <?php
  2.  
  3. mysqli_report(MYSQLI_REPORT_STRICT);
  4.  
  5. function open_database() {
  6. try {
  7. $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
  8. return $conn;
  9. } catch (Exception $e) {
  10. echo $e->getMessage();
  11. return null;
  12. }
  13. }
  14.  
  15. function close_database($conn) {
  16. try {
  17. mysqli_close($conn);
  18. } catch (Exception $e) {
  19. echo $e->getMessage();
  20. }
  21. }
  22.  
  23.  
  24.  
  25. /**
  26. * Pesquisa um Registro pelo ID em uma Tabela
  27. */
  28. function find( $table = null, $id = null ) {
  29.  
  30. $database = open_database();
  31. $found = null;
  32.  
  33. try {
  34. if ($id) {
  35. $sql = "SELECT * FROM " . $table . " WHERE id = " . $id;
  36. $result = $database->query($sql);
  37.  
  38. if ($result->num_rows > 0) {
  39. $found = $result->fetch_assoc();
  40. }
  41.  
  42. } else {
  43.  
  44. $sql = "SELECT * FROM " . $table;
  45. $result = $database->query($sql);
  46.  
  47. if ($result) {
  48. //if ($result->num_rows > 0) {
  49. $found = $result->fetch_all(MYSQLI_ASSOC);
  50. //}
  51. }
  52. }
  53. } catch (Exception $e) {
  54. $_SESSION['message'] = $e->GetMessage();
  55. $_SESSION['type'] = 'danger';
  56. }
  57.  
  58. close_database($database);
  59. return $found;
  60. }
  61.  
  62. /**
  63. * Pesquisa Todos os Registros de uma Tabela
  64. */
  65. function find_all( $table ) {
  66. return find($table);
  67. }
  68.  
  69.  
  70. /**
  71. * Insere um registro no BD
  72. */
  73. function save($table = null, $data = null) {
  74.  
  75. $database = open_database();
  76.  
  77. $columns = null;
  78. $values = null;
  79.  
  80. //print_r($data);
  81.  
  82. foreach ($data as $key => $value) {
  83. $columns .= trim($key, "'") . ",";
  84. $values .= "'$value',";
  85. }
  86.  
  87. // remove a ultima virgula
  88. $columns = rtrim($columns, ',');
  89. $values = rtrim($values, ',');
  90.  
  91. $sql = "INSERT INTO " . $table . "($columns)" . " VALUES " . "($values);";
  92.  
  93. try {
  94. $database->query($sql);
  95.  
  96. $_SESSION['message'] = 'Registro cadastrado com sucesso.';
  97. $_SESSION['type'] = 'success';
  98.  
  99. } catch (Exception $e) {
  100.  
  101. $_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
  102. $_SESSION['type'] = 'danger';
  103. }
  104.  
  105. close_database($database);
  106. }
Add Comment
Please, Sign In to add comment