Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.63 KB | None | 0 0
  1. <?php
  2. /*
  3. This class holds PHP functions for use with databases
  4. */
  5. class Database {
  6. /**
  7. * Creates a backup of the speciefied MySQL database
  8. * @param <string> $host Host computer name where the database is stored
  9. * @param <string> $user Username of the database
  10. * @param <string> $pass Password of the database
  11. * @param <string> $name Database name
  12. * @param <array> $tables (optional) Array of tables that neds to be backed up
  13. * @return <boolean> TRUE if the database backed up successfully
  14. * @category Database
  15. * <code>
  16. * $result = Database::backupDbTables('localhost', 'dbuser', 'p@55word', 'myprefix', '*');
  17. * </code>
  18. */
  19. function backupDbTables($host, $user, $pass, $name, $pref, $tables = '*') {
  20. try {
  21. $link = mysql_connect($host, $user, $pass);
  22. mysql_select_db($name, $link);
  23. //get all of the tables
  24. if ($tables == '*') {
  25. $tables = array();
  26. $result = mysql_query('SHOW TABLES');
  27. while ($row = mysql_fetch_row($result)) {
  28. $tables[] = $row[0];
  29. }
  30. } else {
  31. $tables = is_array($tables) ? $tables : explode(',', $tables);
  32. }
  33. //cycle through
  34. foreach ($tables as $table) {
  35. $result = mysql_query('SELECT * FROM ' . $table);
  36. $numFields = mysql_numFields($result);
  37. $return.= 'DROP TABLE ' . $table . ';';
  38. $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
  39. $return.= "\n\n" . $row2[1] . ";\n\n";
  40. for ($i = 0; $i < $numFields; $i++) {
  41. while ($row = mysql_fetch_row($result)) {
  42. $return.= 'INSERT INTO ' . $table . ' VALUES(';
  43. for ($j = 0; $j < $numFields; $j++) {
  44. $row[$j] = addslashes($row[$j]);
  45. $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
  46. if (isset($row[$j])) {
  47. $return.= '"' . $row[$j] . '"';
  48. } else {
  49. $return.= '""';
  50. }
  51. if ($j < ($numFields - 1)) {
  52. $return.= ',';
  53. }
  54. }
  55. $return.= ");\n";
  56. }
  57. }
  58. $return.="\n\n\n";
  59. }
  60. //save file
  61. $handle = fopen($pref . '-' . time() . '-' . (md5(implode(',', $tables))) . '.sql', 'w+');
  62. fwrite($handle, $return);
  63. fclose($handle);
  64. return TRUE;
  65. } catch (Exception $err) {
  66. return $err->getMessage();
  67. }
  68. }
  69. /**
  70. * Calculates the size of the specified database
  71. * @param <string> $database Name of the database to be calculated
  72. * @return <string> Size of the database
  73. * @category Database
  74. * <code>
  75. * $result = Database::calculateDbSize('db_mydb');
  76. * </code>
  77. */
  78. function calculateDbSize($database) {
  79. try {
  80. $tables = mysql_list_tables($database);
  81. if (!$tables) {
  82. return -1;
  83. }
  84. $tableCount = mysql_num_rows($tables);
  85. $size = 0;
  86. for ($i = 0; $i < $tableCount; $i++) {
  87. $tname = mysql_tablename($tables, $i);
  88. $r = mysql_query("SHOW TABLE STATUS FROM " . $database . " LIKE '" . $tname . "'");
  89. $data = mysql_fetch_array($r);
  90. $size += ( $data['Index_length'] + $data['Data_length']);
  91. };
  92. $units = array(' B', ' KB', ' MB', ' GB', ' TB');
  93. for ($i = 0; $size > 1024; $i++) {
  94. $size /= 1024;
  95. }
  96. return round($size, 2) . $units[$i];
  97. } catch (Exception $err) {
  98. return $err->getMessage();
  99. }
  100. }
  101. /**
  102. * This is the function handler for all my data requests
  103. * @param <string> $query Prepared statement
  104. * @param <array> $params Parameters for the prepare statement
  105. * @param <boolean> $command TRUE if it is an insert, update, delete statement. If FALSE then its a select statement
  106. * @return Multiple values
  107. * @category Database
  108. *
  109. * NOTE: This function needs the refValues function (below) in the same class
  110. *
  111. * <code>
  112. * $result = Database::runCommand("DELETE FROM [tbl_name] WHERE [column] = ?", array("i", 1), TRUE);
  113. * $result = Database::runCommand("INSERT INTO [tbl_name] VALUES (?)", array("i", 1), TRUE);
  114. * $result = Database::runCommand("UPDATE [tbl_name] SET [column_name] = ?", array("i", 1), TRUE);
  115. * $result = Database::runCommand("SELECT * FROM [tbl_Name] WHERE [column] = ?", array("i", 1), FALSE);
  116. *
  117. * echo $result[row_num][$column_name];
  118. * echo count($result);
  119. * </code>
  120. */
  121. function runCommand($query, $params, $command) {
  122. try {
  123. //Setting the default result value
  124. $result = "";
  125. //Configuring the database settings
  126. $hostname = "localhost";
  127. $username = "root";
  128. $password = "";
  129. $database = "db_name";
  130. //Connecting to the database
  131. $mysqli = new mysqli($hostname, $username, $password, $database);
  132. //Checking for errors
  133. if (!mysqli_connect_errno()) {
  134. $stmt = $mysqli->prepare($query);
  135. //Call the function inside of the prepare statement and set all the parameters of the string
  136. if (count($params)) {
  137. call_user_func_array(array($stmt, 'bind_param'), $this->refValues($params));
  138. }
  139. //Executing the statement
  140. $stmt->execute();
  141. //If TRUE, it is an UPDATE,INSERT or DELETE
  142. if ($command) {
  143. //If successful then show the success message
  144. if ($mysqli->affected_rows > 0) {
  145. $result = 'success';
  146. } else {
  147. //Show the error message
  148. $result = " " . $mysqli->error;
  149. }
  150. }
  151. //If FALSE, it is a SELECT statement
  152. else {
  153. //Creating columns for the data
  154. $meta = $stmt->result_metadata();
  155. //Setting the parameter values
  156. while ($field = $meta->fetch_field()) {
  157. $parameters[] = &$row[$field->name];
  158. }
  159. call_user_func_array(array($stmt, 'bind_result'), $this->refValues($parameters));
  160. //Getting the data, creating a two deminsional array
  161. while ($stmt->fetch()) {
  162. $x = array();
  163. $results;
  164. foreach ($row as $key => $val) {
  165. //Creating a key so can get the values
  166. $x[$key] = $val;
  167. }
  168. $results[] = $x;
  169. }
  170. if (!empty($results)) {
  171. $result = $results;
  172. } else {
  173. $result = NULL;
  174. }
  175. }
  176. //Closing the database connection
  177. $mysqli->close();
  178. } else {
  179. //Setting the error message on database connection error
  180. $result = "** Connection to database was unsuccessful";
  181. }
  182. //Returning the result
  183. return $result;
  184. } catch (Exception $err) {
  185. return $err->getMessage();
  186. }
  187. }
  188. /**
  189. * This is to make sure that only the keys are in the arrange for PHP 5.3 +. Used with the function runCommand (above)
  190. * @param <array> $arr Array containing the parameters
  191. * @return <array> Returns a single dimensional array (only keys)
  192. * @category Database
  193. */
  194. function refValues($arr) {
  195. try {
  196. //Reference is required for PHP 5.3+
  197. if (strnatcmp(phpversion(), '5.3') >= 0) {
  198. $refs = array();
  199. foreach ($arr as $key => $value) {
  200. //Saving only the keys to the array and returning a single array
  201. $refs[$key] = &$arr[$key];
  202. }
  203. return $refs;
  204. }
  205. //Return the array
  206. return $arr;
  207. } catch (Exception $err) {
  208. return $err->getMessage();
  209. }
  210. }
  211. }
  212. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement