phpDocumentor GloryLands
Database
[ class tree: GloryLands ] [ index: GloryLands ] [ all elements ]

Source for file db.mysql.php

Documentation is available at db.mysql.php

  1. <?php
  2.  
  3. /** 
  4.   * MySQL Database Jet
  5.   *
  6.   * <pre>
  7.   * GloryLands, a Web-Based, Massive Multiplayer Online RPG/Strategy Game
  8.   * Copyright (C) 2008-09  John Haralampidis <jïhnys2[at]gmail.cïm>
  9.   *
  10.   * This program is free software: you can redistribute it and/or modify
  11.   * it under the terms of the GNU General Public License as published by
  12.   * the Free Software Foundation, either version 3 of the License, or
  13.   * (at your option) any later version.
  14.   *
  15.   * This program is distributed in the hope that it will be useful,
  16.   * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17.   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18.   * GNU General Public License for more details.
  19.   *
  20.   * You should have received a copy of the GNU General Public License
  21.   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  22.   *
  23.   * For any help/suggestions or troubleshooting you can see the
  24.   * project community website at <http://www.glorylands.gr>
  25.   * </pre>
  26.   *
  27.   * @license GNU/GPLv3 GNU General Public License version 3
  28.   * @package GloryLands
  29.   * @subpackage Database
  30.   * @author John Haralampidis <jïhnys2[at]gmail.cïm>
  31.   * @copyright Copyright (C) 2007-2008, John Haralampidis
  32.   * @version 1.0
  33.   */
  34.  
  35. /** 
  36.   * MySQL Database Jet
  37.   *
  38.   * @package GloryLands
  39.   * @subpackage Database
  40.   */
  41. class mysql_jet extends DBJet {
  42.  
  43.     /**
  44.      * Connection ID Definition
  45.      * @var resource 
  46.      */
  47.     var $conID;
  48.  
  49.     /**
  50.      * Description of current action in case of error
  51.      * @var string 
  52.      */
  53.     var $errPosition;
  54.  
  55.     /**
  56.      * Last query's results
  57.      * @var resource 
  58.      */
  59.     var $lastResult;
  60.  
  61.     /**
  62.      * Last query's affected rows
  63.      * @var int 
  64.      */
  65.     var $affectedRows;
  66.     function num_changed(return $numRows}
  67.  
  68.     /**
  69.      * Last query's number of rows
  70.      * @var int 
  71.      */
  72.     var $numRows;
  73.     function num_rows($resultset=false
  74.         if ($resultset === false{
  75.             return $this->numRows
  76.         else {
  77.             return mysql_num_rows($resultset);
  78.         }
  79.     }
  80.  
  81.     /**
  82.      * Last query didn't return any results
  83.      * @var bool 
  84.      */
  85.     var $emptyResults;
  86.  
  87.     /**
  88.      * The number of queries performed
  89.      * @var int 
  90.      */
  91.     var $totQueries;
  92.  
  93.     /**
  94.      * The total time spent on queries
  95.      * @var float 
  96.      */
  97.     var $totTime;
  98.  
  99.     /**
  100.      * If we have global debug enabled, this function will store the
  101.      * queries being executed
  102.      * @var int 
  103.      */
  104.     var $queryList;
  105.  
  106.  
  107.     /**
  108.       * Initializes MySQL Class
  109.       *
  110.       * @param string     $vdb         Database name
  111.       * @param string     $vhost         Database server host
  112.       * @param string     $vuser         Login user name
  113.       * @param string     $vpwd         Login user password
  114.       * @param bool     $presistent Make a presitent connection with the server
  115.       */
  116.     function init($config{
  117.     
  118.         // Get variables from the config
  119.         $vdb $config['DATABASE']
  120.         $vhost $config['HOST'];
  121.         $vuser $config['USER'];
  122.         $vpwd $config['PASSWORD'];
  123.         $presistent false;
  124.         if (isset($config['PRESISTENT'])) $presistent $config['PRESISTENT'];
  125.     
  126.         // Connect to SQL
  127.         $this->totQueries = 0;
  128.         $this->errPosition = "connecting to MySQL";
  129.         if ($presistent{
  130.             $id mysql_pconnect($vhost$vuser$vpwd);
  131.         else {
  132.             $id mysql_connect($vhost$vuser$vpwd);
  133.         }
  134.         if (!$id{
  135.             return false;
  136.         }
  137.         $this->conID = $id;
  138.         
  139.         // Select database
  140.         $this->errPosition = "selecting database '<strong>{$vdb}</strong>'";
  141.         if (!mysql_select_db($vdb$id)) return false;
  142.  
  143.         // Initialize UTF-8
  144.         mysql_query("SET CHARACTER SET 'utf8'");
  145.         mysql_query("SET SESSION collation_connection ='utf8_general_ci'");
  146.         
  147.         // Initialize variables
  148.         $queryList array();
  149.         return true;
  150.     }
  151.  
  152.     /**
  153.       * Performs a query
  154.       *
  155.       * @param string $text Query text to execute
  156.       * @return bool|resourceReturns the query resultset or false in case of error
  157.       */
  158.     function query($text{
  159.         $this->errPosition = "performing query '<strong>{$text}</strong>'";
  160.         $time=microtime(true);
  161.         $result mysql_query($text$this->conID);
  162.         $this->totQueries++;
  163.         if (!$result{
  164.             if (defined("GLOB_DEBUG")) $this->queryList[]=array('query'=>$text,'result'=>false,'error'=>$this->get_error_message());
  165.             //debug_error($this->get_error_message(),ERR_WARNING);
  166.             $this->emptyResults = true;
  167.             $this->totTime+=(microtime(true)-$time);
  168.             return false;
  169.         }
  170.         $this->lastResult = $result
  171.         if ((substr(strtoupper($text),6== "SELECT"|| (substr(strtoupper($text),4== "SHOW")) 
  172.             $this->numRows = mysql_num_rows($result);
  173.             $this->emptyResults = ($this->numRows == 0);
  174.             if (defined("GLOB_DEBUG")) $this->queryList[]=array('query'=>$text,'result'=>true,'rows'=>$this->numRows);
  175.         else 
  176.             $this->affectedRows = mysql_affected_rows();        
  177.             $this->emptyResults = ($this->affectedRows == 0);
  178.             if (defined("GLOB_DEBUG")) $this->queryList[]=array('query'=>$text,'result'=>true,'rows'=>$this->affectedRows);
  179.         }
  180.         $this->totTime+=(microtime(true)-$time);
  181.         return $result;
  182.     }    
  183.     
  184.     /**
  185.       * Return the first value of the first row of the requested query, using a specified resultset
  186.       *
  187.       * @param resource $result    (optional) Resultset obdained from a query() or query-like function
  188.       * @return bool|resourceReturns the value or false in case of error
  189.       */
  190.     function fetch_value($result=false{
  191.         if (!$result{
  192.             $respond mysql_fetch_array($this->lastResultMYSQL_NUM)
  193.         else {
  194.             $respond mysql_fetch_array($resultMYSQL_NUM)
  195.             return $respond[0];        
  196.         }
  197.     }
  198.  
  199.     /**
  200.       * Release a specific query resultset
  201.       *
  202.       * @param resource $resultset    Resultset obdained from query() function
  203.       */
  204.     function free_query($resultset{
  205.         mysql_free_result($resultset);
  206.     }
  207.  
  208.     /**
  209.       * Return a row from the last queried resultset
  210.       *
  211.       * @param int $resmode    The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of MYSQL_BOTH
  212.       * @return bool|resourceReturns the row or false in case of error or end of results
  213.       */
  214.     function fetch_array($resmode MYSQL_BOTH$resultset false{
  215.         if (!$resultset$resultset=$this->lastResult;
  216.         if (!$resultsetreturn false;
  217.         return mysql_fetch_array($resultset$resmode)
  218.     }
  219.  
  220.     /**
  221.       * Return all the rows from the last queried resultset
  222.       *
  223.       * @param int $resmode    The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of MYSQL_BOTH
  224.       * @return bool|resourceReturns the row or false in case of error or end of results
  225.       */
  226.     function fetch_array_all($resmode MYSQL_BOTH$resultset false{
  227.         if (!$resultset$resultset=$this->lastResult;
  228.         if (!$resultsetreturn array();
  229.         
  230.         $res array();
  231.         while ($row mysql_fetch_array($resultset$resmode)) {
  232.             array_push($res$row);
  233.         }
  234.         return $res;
  235.     }
  236.     
  237.     /**
  238.       * Release the last queried resultset
  239.       */
  240.     function free_results({
  241.         if (!mysql_free_result($this->lastResult)) return false;
  242.         return true;
  243.     }
  244.     
  245.     /**
  246.       * Moves the internal row pointer to a new position
  247.       *
  248.       * @param int $row    The row index to jump to
  249.       */
  250.     function set_row($row$resultset=false{
  251.         if (!$resultset$resultset=$this->lastResult;
  252.         if (!mysql_data_seek($resultset$row)) return false;
  253.         return true;
  254.     }
  255.     
  256.     /**
  257.       * Returns detailed information for the last error occured
  258.       *
  259.       * @param bool $formatted    (optional) TRUE If you want the result to be a pre-formatted HTML response
  260.       * @return string    An HTML-Formatted error description
  261.       */
  262.     function get_error_message($formatted=true{
  263.         if ($formatted{
  264.             return "<font face=Arial size=1 color=red>MySQL error while " $this->errPosition . " : <font color=blue>" mysql_error("</font></font>";
  265.         else {
  266.             return mysql_error();
  267.         }
  268.     }
  269.  
  270.     /**
  271.       * Insert a new row on specified table
  272.       *
  273.       * @param string $table    The table name to add the data
  274.       * @param array $data        An one-dimensional array that contains the field names (as keys) and the field values to add
  275.       * @return bool|resource   Returns false in case of error or the resultset of the executed query
  276.       */
  277.     function insert($table$data{
  278.         $vars ""$vals "";
  279.         foreach ($data as $name => $value{
  280.             if ($vars != ""$vars .= ", ";
  281.             if ($vals != ""$vals .= ", ";
  282.             
  283.             $vars .= "`{$name}`";
  284.             $vals .= "'".mysql_real_escape_string($value)."'";
  285.         }
  286.         
  287.         return $this->query("INSERT INTO `{$table}` ({$vars}VALUES ({$vals})");
  288.     }
  289.  
  290.     /**
  291.       * Replace or insert a new row on specified table
  292.       *
  293.       * @param string $table    The table name to add the data
  294.       * @param array $data        An one-dimensional array that contains the field names (as keys) and the field values to add
  295.       * @return bool|resource   Returns false in case of error or the resultset of the executed query
  296.       */
  297.     function replace($table$data{
  298.         $vars ""$vals "";
  299.         foreach ($data as $name => $value{
  300.             if ($vars != ""$vars .= ", ";
  301.             if ($vals != ""$vals .= ", ";
  302.             
  303.             $vars .= "`{$name}`";
  304.             $vals .= "'".mysql_real_escape_string($value)."'";
  305.         }
  306.         
  307.         return $this->query("REPLACE INTO `{$table}` ({$vars}VALUES ({$vals})");
  308.     }
  309.  
  310.     /**
  311.       * Performs a query and returns true if the results are not empty
  312.       *
  313.       * @param string $query    The query to execute
  314.       * @return bool            Returns false in case of error or empty resultset, or true otherways
  315.       */
  316.     function poll($query{
  317.         $this->errPosition = "performing polling query '<strong>{$query}</strong>'";
  318.         $time=microtime(true);
  319.         $result mysql_query($query$this->conID);
  320.         $this->totQueries++;
  321.         if (!$result{
  322.             if (defined("GLOB_DEBUG")) $this->queryList[]=array('query'=>$text,'result'=>false,'error'=>$this->get_error_message());
  323.             //debug_error($this->get_error_message(),ERR_WARNING);
  324.             $this->totTime+=(microtime(true)-$time);
  325.             return false;
  326.         else {
  327.             if (defined("GLOB_DEBUG")) $this->queryList[]=array('query'=>$text,'result'=>true,'rows'=>mysql_num_rows($result));
  328.         }
  329.         $ans (mysql_num_rows($result)!=0);
  330.         mysql_free_result($result);
  331.         $this->totTime+=(microtime(true)-$time);
  332.         return $ans;
  333.     }
  334.     
  335.     /**
  336.       * Performs a query and returns the first value of the first row or false in case of error
  337.       *
  338.       * @param string $query    The query to execute
  339.       * @return bool|string       Returns false in case of error or the first row's first field value
  340.       */
  341.     function query_and_get_value($query{
  342.         $this->errPosition = "performing get value query '<strong>".htmlspecialchars($query)."</strong>'";
  343.         $time=microtime(true);
  344.         $result mysql_query($query$this->conID);
  345.         $this->totQueries++;
  346.         if (!$result{
  347.             if (defined("GLOB_DEBUG")) $this->queryList[]=array('query'=>$text,'result'=>false,'error'=>$this->get_error_message());
  348.             //debug_error($this->get_error_message(),ERR_WARNING);
  349.             $this->totTime+=(microtime(true)-$time);
  350.             return false;
  351.         else {
  352.             if (defined("GLOB_DEBUG")) $this->queryList[]=array('query'=>$text,'result'=>true,'rows'=>mysql_num_rows($result));
  353.         }
  354.         if (mysql_num_rows($result)==0return "";
  355.         $row=mysql_fetch_array($resultMYSQL_NUM);
  356.         mysql_free_result($result);
  357.         $this->totTime+=(microtime(true)-$time);
  358.         return $row[0];
  359.     }
  360.  
  361.     /**
  362.       * Update a row on a table. The row to edit is defined by a where clause
  363.       *
  364.       * @param string $table    The table name from which to edit the data
  365.       * @param string $where    A MySQL WHERE-formatted query part. This is used to identify the item(s) to edit (ex. "`index` = 2")
  366.       * @param array $data        An one-dimensional array that contains the field names (as keys) and the field values to edit
  367.       * @return bool|resource   Returns false in case of error or the resultset of the executed query
  368.       */
  369.     function update($table$index_data$insert_data{
  370.         if (is_array($index_data)) {
  371.             $data '';
  372.             foreach ($index_data as $n => $v{
  373.                 if ($data!=''$data.=' AND ';
  374.                 $data.='`'.$n.'` = \''.mysql_real_escape_string($v).'\'';
  375.             }
  376.             $where=$data;
  377.         else {
  378.             $where=$index_data;
  379.         }
  380.  
  381.         $q "";
  382.         foreach ($insert_data as $name => $value{
  383.             if ($q != ""$q .= ", ";
  384.             $q .= "`{$name}` = '".mysql_real_escape_string($value)."'";
  385.         }
  386.         return $this->query("UPDATE `{$table}SET {$q} WHERE {$where}");
  387.     }
  388.  
  389.     /**
  390.       * Remove one or more rows from a table.
  391.       *
  392.       * @param string $table    The table name from which to edit the data
  393.       * @param string $where    A MySQL WHERE-formatted query part or an array containing the indexing values
  394.       * @return bool|resource   Returns false in case of error or the resultset of the executed query
  395.       */
  396.     function delete($table$index_data=false{
  397.         if (is_array($index_data)) {
  398.             $data '';
  399.             foreach ($index_data as $n => $v{
  400.                 if ($data!=''$data.=' AND ';
  401.                 if (strstr($v,'%')) {
  402.                     $data .= "`{$n}LIKE '".mysql_real_escape_string($v)."'";
  403.                 else {
  404.                     $data .= "`{$n}` = '".mysql_real_escape_string($v)."'";
  405.                 }
  406.                 //$data.='`'.$n.'` = \''.mysql_escape_string($v).'\'';
  407.             }
  408.             $where=$data;
  409.         elseif ($index_data===false{
  410.             $where='';
  411.         else {
  412.             $where=$index_data;
  413.         }
  414.  
  415.         return $this->query("DELETE FROM `{$table}WHERE {$where}");
  416.     }
  417.  
  418.     /**
  419.       * Select one or more rows from a table.
  420.       *
  421.       * @param string $table        The table name from which to edit the data
  422.       * @param string $index_data    A MySQL WHERE-formatted query part or an array containing the indexing values
  423.       * @param string $return_data    A MySQL SELECT-formatted query part or an array containing the values to return
  424.       * @return bool|resource       Returns false in case of error or the resultset of the executed query
  425.       */
  426.     function select($table$index_data=false$return_data=false$order_by=false$sort_order=false{
  427.         if (is_array($return_data)) {
  428.             $data '';
  429.             foreach ($return_data as $v{
  430.                 if ($data!=''$data.=',';
  431.                 $data.='`'.$v.'`';
  432.             }
  433.             $what=$data;
  434.         elseif ($return_data===false{
  435.             $what='*';
  436.         else {
  437.             $what=$return_data;
  438.         }
  439.  
  440.         if (is_array($index_data)) {
  441.             $data '';
  442.             foreach ($index_data as $n => $v{
  443.                 if ($data!=''$data.=' AND ';
  444.                 if (strstr($v,'%')) {
  445.                     $data .= "`{$n}LIKE '".mysql_real_escape_string($v)."'";
  446.                 else {
  447.                     $data .= "`{$n}` = '".mysql_real_escape_string($v)."'";
  448.                 }
  449.                 //$data.='`'.$n.'` = \''.mysql_escape_string($v).'\'';
  450.             }
  451.             $where=' WHERE '.$data;
  452.         elseif ($index_data===false{
  453.             $where='';
  454.         else {
  455.             $where=' WHERE '.$index_data;
  456.         }
  457.  
  458.         $order '';
  459.         if ($order_by !== false{
  460.             $ord 'ASC';
  461.             if ($sort_order !== false{
  462.                 $ord mysql_escape_string($sort_order);
  463.             }
  464.             $order ' ORDER BY `'.mysql_real_escape_string($order_by).'` '.$ord;
  465.         }
  466.  
  467.         return $this->query("SELECT {$what} FROM `{$table}` {$where}{$order}");
  468.     }
  469.  
  470.     /**
  471.       * List the database tables
  472.       *
  473.       * @return bool|array       Returns false in case of error or the tables as array
  474.       */
  475.     function get_tables({
  476.         // Query
  477.         $ans=$this->query("show tables");
  478.         if (!$ansreturn false;
  479.         
  480.         // Store tables
  481.         $tables array();
  482.         while ($row $this->fetch_array(MYSQL_NUM,$ans)) {
  483.             $tables[$row[0];
  484.         }
  485.         
  486.         // Return result
  487.         return $tables;
  488.     }
  489.     
  490.     /**
  491.       * Show the database structure
  492.       *
  493.       * @param    string    $table    The table name
  494.       * @return bool|array       Returns false in case of error or the table columns as associative array (Key = column name)
  495.       */
  496.     function get_table_structure($table{
  497.         // Query
  498.         $ans=$this->query("show columns from `".$table."`");
  499.         if (!$ansreturn false;
  500.         
  501.         // Store columns
  502.         $columns array();
  503.         while ($row $this->fetch_array(MYSQL_ASSOC,$ans)) {
  504.             $name $row['Field'];
  505.             $columns[$name$row;
  506.         }
  507.         
  508.         // Return result
  509.         return $columns;
  510.     }
  511.  
  512.     /**
  513.       * Converts a UNIX timestamp into SQL timestamp
  514.       *
  515.       * @param int $timestamp    A UNIX timestamp value
  516.       * @return string            Returns the value into MySQL timestamp format
  517.       */
  518.     function SQLTime($timestamp{
  519.         return date("YmdHis"$timestamp);        
  520.     }
  521.  
  522.     /**
  523.       * Converts a UNIX timestamp into SQL timestamp
  524.       *
  525.       * @param string $timestamp    A MySQL timestamp value
  526.       * @return int                    Returns the value into UNIX timestamp format
  527.       */
  528.     function UNIXTime($timestamp{
  529.         $y substr($timestamp,0,4);
  530.         $m substr($timestamp,4,2);
  531.         $d substr($timestamp,6,2);
  532.         $h substr($timestamp,8,2);
  533.         $i substr($timestamp,10,2);
  534.         $s substr($timestamp,12,2);
  535.         return mktime($h$i$s$m$d$y);        
  536.     }
  537.     
  538.     /**
  539.       * Execute a SQL script
  540.       *
  541.       * @param string $file        The filename to load and run
  542.       * @return bool            Returns true if all the queries were successfull or false if one query failed
  543.       */
  544.     function run($file{
  545.     
  546.         // Open file
  547.         $f fopen($file,"r");
  548.         if (!$freturn;
  549.         
  550.         // Read file
  551.         $incomment false;
  552.         $buffer '';
  553.         while (!feof($f)) {
  554.             $row trim(fgets($f4096));
  555.             if ((substr($row,0,1)!='#'&& (substr($row,0,2)!='--')) {
  556.                 if (substr($row,0,2== '/*'$incomment true;
  557.                 if (!$incomment{
  558.                     $buffer .= $row."\n";
  559.                 }
  560.                 if (substr($row,-2== '*/'$incomment false;
  561.             }
  562.         }
  563.         fclose($f);
  564.         
  565.         // Count queries
  566.         $success 0;
  567.         
  568.         // Break file queries
  569.         $queries explode(";\n"$buffer);
  570.         foreach ($queries as $query{
  571.             if (trim($query)!=''{
  572.                 if (!$this->query($query)) return false;
  573.             }
  574.         }
  575.  
  576.         return true;
  577.     }
  578.  
  579.     /**
  580.       * Visualize the queries being executed for debug purposes
  581.       *
  582.       * @return string    Returns an HTML formatted result with the queries and their status
  583.       */
  584.     function getQueries({
  585.         $ans '<table border="1" width="100%">';
  586.         foreach ($this->queryList as $query{
  587.             $ans .= '<tr><td>'.$query['query'].'</td>';
  588.             if ($query['result']{
  589.                 $ans .= '<td><font color="green">OK</font></td>';
  590.                 $ans .= '<td>Returned/Affected '.$query['rows'].' rows</td>';
  591.             else {
  592.                 $ans .= '<td colspan="2">'.$query['error'].'</td>';
  593.             }
  594.             $ans .= '</tr>';
  595.         }
  596.         $ans .= '</table>';
  597.         return $ans;
  598.     }
  599.      
  600. }
  601.  
  602. ?>

Documentation generated on Tue, 13 Oct 2009 23:48:46 +0300 by phpDocumentor 1.4.1