IAL32

DB Class

Oct 3rd, 2013
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.91 KB | None | 0 0
  1. <?
  2.     /** A PHP class to access MySQL database with convenient methods
  3.         * in an object oriented way, and with a powerful debug system.\n
  4.         * Licence:  LGPL \n
  5.         * Web site: http://slaout.linux62.org/
  6.         * @version  1.0
  7.         * @author   S&eacute;bastien Lao&ucirc;t ([email protected])
  8.         */
  9.     class dbNormal {
  10.         /** Put this variable to true if you want ALL queries to be debugged by default:
  11.         */
  12.         var $defaultDebug = false;
  13.         /** INTERNAL: The start time, in miliseconds.
  14.         */
  15.         var $mtStart;
  16.         /** INTERNAL: The number of executed queries.
  17.         */
  18.         var $nbQueries;
  19.         /** INTERNAL: The last result ressource of a query().
  20.         */
  21.         var $lastResult;
  22.         /** Connect to a MySQL database to be able to use the methods below.
  23.           */
  24.         function dbNormal($server, $user, $pass, $base) {
  25.             $this->mtStart    = $this->getMicroTime();
  26.             $this->nbQueries  = 0;
  27.             $this->lastResult = NULL;
  28.             mysql_connect($server, $user, $pass)
  29.                 or die('Server connexion not possible.');
  30.             mysql_select_db($base)
  31.                 or die('Database connexion not possible.');
  32.         }
  33.         /*
  34.             @param $table The table where to insert the data
  35.             @param $data  The data to be inserted in array format
  36.             @return       The last inserted ID
  37.         */
  38.         function insert($table, $data) {
  39.             foreach ($data as $key => $value) {
  40.                 $fields .= $key . ",";
  41.                 if(!is_int($value)) {
  42.                     $value = '"' . $value . '"';
  43.                 }
  44.                 $values .= $value . ",";
  45.             }
  46.             $fields = substr($fields, 0, -1);
  47.             $values = substr($values, 0, -1);
  48.             $this->execute("INSERT INTO {$table} ({$fields}) VALUES ({$values})");
  49.             return $this->lastInsertedId();
  50.         }
  51.         function update($table, $data, $condition) {
  52.             foreach ($data as $key => $value) {
  53.                 if(!is_int($value)) {
  54.                      $value = '"' . $value . '"';
  55.                  }
  56.                     $fields .= $key . "=" . $value . ",";
  57.             }
  58.             $fields = substr($fields, 0, -1);
  59.             $this->execute("UPDATE {$table} SET {$fields} WHERE {$condition}");
  60.         }
  61.         /* Fetching the result
  62.             @param $result The resource returned by query(). If NULL, the last result returned by query() will be used.
  63.             @param $res_type Choose between MYSQL_BOTH, MYSQL_NUM, MYSQL_ASSOC
  64.             @return A array representing the result
  65.         */
  66.         function arrFetch($result = NULL, $res_type = MYSQL_BOTH) {
  67.             if($result == null)
  68.                 return $this->lastResult;
  69.             else
  70.                 return mysql_fetch_array($result, $res_type);
  71.         }
  72.         /** Query the database.
  73.           * @param $query The query.
  74.           * @param $debug If true, it output the query and the resulting table.
  75.           * @return The result of the query, to use with fetchNextObject().
  76.         */
  77.         function query($query, $debug = -1) {
  78.             $this->nbQueries++;
  79.             $this->lastResult = mysql_query($query) or $this->debugAndDie($query);
  80.             $this->debug($debug, $query, $this->lastResult);
  81.             return $this->lastResult;
  82.         }
  83.         /** Do the same as query() but do not return or store result.\n
  84.           * Should be used for INSERT, UPDATE, DELETE...
  85.           * @param $query The query.
  86.           * @param $debug If true, it output the query and the resulting table.
  87.         */
  88.         function execute($query, $debug = -1) {
  89.             $this->nbQueries++;
  90.             mysql_query($query) or $this->debugAndDie($query);
  91.             $this->debug($debug, $query);
  92.         }
  93.         /** Convenient method for mysql_fetch_object().
  94.           * @param $result The ressource returned by query(). If NULL, the last result returned by query() will be used.
  95.           * @return An object representing a data row.
  96.           */
  97.         function fetchNextObject($result = NULL) {
  98.             if($result == NULL)
  99.                 $result = $this->lastResult;
  100.             if($result == NULL || mysql_num_rows($result) < 1)
  101.                 return NULL;
  102.             else
  103.                 return mysql_fetch_object($result);
  104.         }
  105.         /** Get the number of rows of a query.
  106.           * @param $result The ressource returned by query(). If NULL, the last result returned by query() will be used.
  107.           * @return The number of rows of the query (0 or more).
  108.         */
  109.         function numRows($result = NULL) {
  110.             if ($result == NULL)
  111.                 return mysql_num_rows($this->lastResult);
  112.             else
  113.                 return mysql_num_rows($result);
  114.         }
  115.         /** Get the result of the query as an object. The query should return a unique row.\n
  116.           * Note: no need to add "LIMIT 1" at the end of your query because
  117.           * the method will add that (for optimisation purpose).
  118.           * @param $query The query.
  119.           * @param $debug If true, it output the query and the resulting row.
  120.           * @return An object representing a data row (or NULL if result is empty).
  121.         */
  122.         function queryUniqueObject($query, $debug = -1) {
  123.             $query = "$query LIMIT 1";
  124.             $this->nbQueries++;
  125.             $result = mysql_query($query) or $this->debugAndDie($query);
  126.             $this->debug($debug, $query, $result);
  127.             return mysql_fetch_object($result);
  128.         }
  129.         /** Get the result of the query as value. The query should return a unique cell.\n
  130.           * Note: no need to add "LIMIT 1" at the end of your query because
  131.           * the method will add that (for optimisation purpose).
  132.           * @param $query The query.
  133.           * @param $debug If true, it output the query and the resulting value.
  134.           * @return A value representing a data cell (or NULL if result is empty).
  135.         */
  136.         function queryUniqueValue($query, $debug = -1) {
  137.             $query = "$query LIMIT 1";
  138.             $this->nbQueries++;
  139.             $result = mysql_query($query) or $this->debugAndDie($query);
  140.             $line = mysql_fetch_row($result);
  141.             $this->debug($debug, $query, $result);
  142.             return $line[0];
  143.         }
  144.         /** Get the result of the query as array.\n
  145.           * Note: no need to add "LIMIT 1" at the end of your query because
  146.           * the method will add that (for optimisation purpose).
  147.           * @param $query The query.
  148.           * @param $debug If true, it output the query and the resulting value.
  149.           * @return A value representing the data array.
  150.         */
  151.         function queryUniqueRow($query, $res_type = MYSQL_BOTH, $debug = -1) {
  152.             $query = "$query LIMIT 1";
  153.             $this->nbQueries++;
  154.             $result = mysql_query($query) or $this->debugAndDie($query);
  155.             $row = $this->arrFetch($result, $res_type);
  156.             $this->debug($debug, $query, $result);
  157.             return $row;
  158.         }
  159.         /** Get the maximum value of a column in a table, with a condition.
  160.           * @param $column The column where to compute the maximum.
  161.           * @param $table The table where to compute the maximum.
  162.           * @param $where The condition before to compute the maximum.
  163.           * @return The maximum value (or NULL if result is empty).
  164.         */
  165.         function maxOf($column, $table, $where) {
  166.             return $this->queryUniqueValue("SELECT MAX(`$column`) FROM `$table` WHERE $where");
  167.         }
  168.         /** Get the maximum value of a column in a table.
  169.           * @param $column The column where to compute the maximum.
  170.           * @param $table The table where to compute the maximum.
  171.           * @return The maximum value (or NULL if result is empty).
  172.         */
  173.         function maxOfAll($column, $table) {
  174.             return $this->queryUniqueValue("SELECT MAX(`$column`) FROM `$table`");
  175.         }
  176.         /** Get the count of rows in a table, with a condition.
  177.           * @param $table The table where to compute the number of rows.
  178.           * @param $where The condition before to compute the number or rows.
  179.           * @return The number of rows (0 or more).
  180.         */
  181.         function countOf($table, $where) {
  182.             return $this->queryUniqueValue("SELECT COUNT(*) FROM `$table` WHERE $where");
  183.         }
  184.         /** Get the count of rows in a table.
  185.           * @param $table The table where to compute the number of rows.
  186.           * @return The number of rows (0 or more).
  187.           */
  188.         function countOfAll($table) {
  189.             return $this->queryUniqueValue("SELECT COUNT(*) FROM `$table`");
  190.         }
  191.         /** Internal function to debug when MySQL encountered an error,
  192.           * even if debug is set to Off.
  193.           * @param $query The SQL query to echo before diying.
  194.           */
  195.         function debugAndDie($query) {
  196.             $this->debugQuery($query, "Error");
  197.             die("<p style=\"margin: 2px;\">".mysql_error()."</p></div>");
  198.         }
  199.         /** Internal function to debug a MySQL query.\n
  200.           * Show the query and output the resulting table if not NULL.
  201.           * @param $debug The parameter passed to query() functions. Can be boolean or -1 (default).
  202.           * @param $query The SQL query to debug.
  203.           * @param $result The resulting table of the query, if available.
  204.         */
  205.         function debug($debug, $query, $result = NULL) {
  206.             if($debug === -1 && $this->defaultDebug === false)
  207.                 return;
  208.             if($debug === false)
  209.                 return;
  210.             $reason = ($debug === -1 ? "Default Debug" : "Debug");
  211.             $this->debugQuery($query, $reason);
  212.             if ($result == NULL)
  213.                 echo "<p style=\"margin: 2px;\">Number of affected rows: ".mysql_affected_rows()."</p></div>";
  214.             else
  215.                 $this->debugResult($result);
  216.         }
  217.         /** Internal function to output a query for debug purpose.\n
  218.           * Should be followed by a call to debugResult() or an echo of "</div>".
  219.           * @param $query The SQL query to debug.
  220.           * @param $reason The reason why this function is called: "Default Debug", "Debug" or "Error".
  221.         */
  222.         function debugQuery($query, $reason = "Debug") {
  223.             $color = ($reason == "Error" ? "red" : "orange");
  224.             echo "<div style=\"border: solid $color 1px; margin: 2px;\">".
  225.                 "<p style=\"margin: 0 0 2px 0; padding: 0; background-color: #DDF;\">".
  226.                 "<strong style=\"padding: 0 3px; background-color: $color; color: white;\">$reason:</strong> ".
  227.                 "<span style=\"font-family: monospace;\">".htmlentities($query)."</span></p>";
  228.         }
  229.         /** Internal function to output a table representing the result of a query, for debug purpose.\n
  230.           * Should be preceded by a call to debugQuery().
  231.           * @param $result The resulting table of the query.
  232.         */
  233.         function debugResult($result) {
  234.             echo "<table border=\"1\" style=\"margin: 2px;\">".
  235.                "<thead style=\"font-size: 80%\">";
  236.             $numFields = mysql_num_fields($result);
  237.             // BEGIN HEADER
  238.             $tables    = array();
  239.             $nbTables  = -1;
  240.             $lastTable = "";
  241.             $fields    = array();
  242.             $nbFields  = -1;
  243.             while ($column = mysql_fetch_field($result)) {
  244.                 if($column->table != $lastTable) {
  245.                     $nbTables++;
  246.                     $tables[$nbTables] = array("name" => $column->table, "count" => 1);
  247.                 } else $tables[$nbTables]["count"]++;
  248.                 $lastTable = $column->table;
  249.                 $nbFields++;
  250.                 $fields[$nbFields] = $column->name;
  251.             }
  252.             for ($i = 0; $i <= $nbTables; $i++)
  253.                 echo "<th colspan=".$tables[$i]["count"].">".$tables[$i]["name"]."</th>";
  254.             echo "</thead>";
  255.             echo "<thead style=\"font-size: 80%\">";
  256.             for ($i = 0; $i <= $nbFields; $i++)
  257.                 echo "<th>".$fields[$i]."</th>";
  258.             echo "</thead>";
  259.             // END HEADER
  260.             while ($row = mysql_fetch_array($result)) {
  261.                 echo "<tr>";
  262.                 for ($i = 0; $i < $numFields; $i++)
  263.                     echo "<td>".htmlentities($row[$i])."</td>";
  264.                 echo "</tr>";
  265.             }
  266.             echo "</table></div>";
  267.             $this->resetFetch($result);
  268.         }
  269.         /** Get how many time the script took from the begin of this object.
  270.           * @return The script execution time in seconds since the
  271.           * creation of this object.
  272.         */
  273.         function getExecTime() {
  274.             return round(($this->getMicroTime() - $this->mtStart) * 1000) / 1000;
  275.         }
  276.         /** Get the number of queries executed from the begin of this object.
  277.           * @return The number of queries executed on the database server since the
  278.           * creation of this object.
  279.         */
  280.         function getQueriesCount() {
  281.             return $this->nbQueries;
  282.         }
  283.         /** Go back to the first element of the result line.
  284.           * @param $result The resssource returned by a query() function.
  285.           */
  286.         function resetFetch($result) {
  287.             if(mysql_num_rows($result) > 0)
  288.                 mysql_data_seek($result, 0);
  289.         }
  290.         /** Get the id of the very last inserted row.
  291.           * @return The id of the very last inserted row (in any table).
  292.         */
  293.         function lastInsertedId() {
  294.             return mysql_insert_id();
  295.         }
  296.         /** Close the connexion with the database server.\n
  297.           * It's usually unneeded since PHP do it automatically at script end.
  298.           */
  299.         function close() {
  300.             mysql_close();
  301.         }
  302.  
  303.         /** Internal method to get the current time.
  304.           * @return The current time in seconds with microseconds (in float format).
  305.           */
  306.         function getMicroTime() {
  307.             list($msec, $sec) = explode(' ', microtime());
  308.             return floor($sec / 1000) + $msec;
  309.         }
  310.     } // class DB
  311. ?>
Advertisement
Add Comment
Please, Sign In to add comment