php 写mysql查询日志

1global.func.php

<?php

function daddslashes($string, $force = 0) {

       

	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());

        //echo  MAGIC_QUOTES_GPC;

	if(!MAGIC_QUOTES_GPC || $force) {

		if(is_array($string)) {

			foreach($string as $key => $val) {

				$string[$key] = daddslashes($val, $force);

			}

		} else {

                       

			$string = addslashes($string);

                       

		}

                 

	}

         

	return $string;

}



//设置dcookie

function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {

	global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;

	$var = ($prefix ? $cookiepre : '').$var;

	if($value == '' || $life < 0) {

		$value = '';

		$life = -1;

	}

	$life = $life > 0 ? $timestamp + $life : ($life < 0 ? $timestamp - 31536000 : 0);

	$path = $httponly && PHP_VERSION < '5.2.0' ? "$cookiepath; HttpOnly" : $cookiepath;

	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;

	if(PHP_VERSION < '5.2.0') {

		setcookie($var, $value, $life, $path, $cookiedomain, $secure);

	} else {

		setcookie($var, $value, $life, $path, $cookiedomain, $secure, $httponly);

	}

}



define("LOG_PATH",dirname(__FILE__));

function glogs($logName, $log) {

    

    $file =   $logName . '.log';

 

    $hd = fopen ( $file, 'a+' );

    $log =   '    '  . $log . "\n";

    

    fwrite ( $hd, $log );

    fclose ( $hd );

}



function dblogs($log,$runTime="",$result=1,$type="ms" )

{

    //$runTime为秒

    $typeArr=array("ms"=>"毫秒",'s'=>"秒");

    $resultArr=array("0"=>"error","1"=>"ok");

    

   if(!array_key_exists($result, $resultArr))

    return ;

   

    $dateStr=date("Y-m-d H:i:s");

    $log=$dateStr." ".$resultArr[$result]." ". $log;

    if($type=="ms"){

         $runTime=floatval($runTime)*1000;

        

    }

    else

    { 

        

    }

    $log.= "  [".$runTime." ". $typeArr[$type].  "]";

  

    

    glogs("dblogs", $log);

    

}





?>

 2 mysqlHelper.class.php

<?php



/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */



/**

 * 

 * 使用前使用

 * MysqlHelper::$charset = 'utf8';

 * MysqlHelper::connect($dbhost, $dbuser, $dbpw, $dbname );

 * 

 * Description of mysqlHelper

 * mysql数据库操作类

 *

 * @author zhoujian

 * @date    2011-08-31

 */

class MysqlHelper {

  	private static $querynum = 0;

	private static $link;

	public static $charset;

        

        

        static  function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $halt = TRUE) {

            

            

                if(self::$link!=null)//如果已经连接过了,直接返回

                    return ;

                //echo "runned";

                  if(D_BUG) {

			

			$sqlstarttime = $sqlendttime = 0;

                        //echo microtime();

			$mtime = explode(' ', microtime());

			$sqlstarttime = $mtime[1]+ $mtime[0] ;

                        

 

                }     

		if($pconnect) {

			if(!self::$link = @mysql_pconnect($dbhost, $dbuser, $dbpw, 1)) {

				$halt && self::halt('Can not connect to MySQL server');

			}

		} else {

			if(!self::$link = @mysql_connect($dbhost, $dbuser, $dbpw, 1)) {

				$halt && self::halt('Can not connect to MySQL server');

			}

		}

                if(D_BUG)

                    {

                        $mtime = explode(' ', microtime());

			$sqlendttime =  $mtime[1] + $mtime[0]  ;

			$sqlQueryTime = number_format($sqlendttime - $sqlstarttime,6);

                        dblogs("connection to Mysql[".$dbhost."]" , $sqlQueryTime,1);

                         

                         

                    }

                

		if(self::version() > '4.1') {

			if(self::$charset) {

                                $tmp_Charset=self::$charset;

                                //echo "SET character_set_connection=${tmp_Charset}, character_set_results=${tmp_Charset}, character_set_client=binary";

				@mysql_query("SET character_set_connection=$tmp_Charset, character_set_results=$tmp_Charset, character_set_client=binary", self::$link);

			}

			if(self::version() > '5.0.1') {

				@mysql_query("SET sql_mode=''", self::$link);

			}

		}

		if($dbname) {

			self::select_db($dbname, self::$link);

                        

		}

	}



	 static function select_db($dbname) {

                 if(D_BUG) {

			

			$sqlstarttime = $sqlendttime = 0;

                        //echo microtime();

			$mtime = explode(' ', microtime());

			$sqlstarttime = $mtime[1]+ $mtime[0] ;

                        

 

                }     

                 

		$result=mysql_select_db($dbname, self::$link);

                if($result)

                {

                 if(D_BUG) {

                       // sleep(1);

			$mtime = explode(' ', microtime());

			$sqlendttime =  $mtime[1] + $mtime[0]  ;

			$sqlQueryTime = number_format($sqlendttime - $sqlstarttime,6);   

                        dblogs("Mysql switch to db[".$dbname."]" , $sqlQueryTime,1);

                 }

                }

                else

                {  if(D_BUG)

                    {

                        $mtime = explode(' ', microtime());

			$sqlendttime =  $mtime[1] + $mtime[0]  ;

			$sqlQueryTime = number_format($sqlendttime - $sqlstarttime,6);   

                       

                    

                        dblogs("MySQL switch db Error", $sqlQueryTime,0);

                    }

		    self::halt('MySQL switch db Error');

                    

                }   

                 return $result;

                

	}



	static function fetch_array($query, $result_type = MYSQL_ASSOC) {

		return mysql_fetch_array($query, $result_type);

	}



	static function query($sql, $type = '') {

		if(D_BUG) {

			

			$sqlstarttime = $sqlendttime = 0;

                        //echo microtime();

			$mtime = explode(' ', microtime());

			$sqlstarttime = $mtime[1]+ $mtime[0] ;

                        

 

		}

		$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?

			'mysql_unbuffered_query' : 'mysql_query';

		if(!($query = $func($sql, self::$link)) && $type != 'SILENT') {

                    

                      

                    if(D_BUG)

                    {

                        $mtime = explode(' ', microtime());

			$sqlendttime =  $mtime[1] + $mtime[0]  ;

			$sqlQueryTime = number_format($sqlendttime - $sqlstarttime,6);

                        dblogs($sql, $sqlQueryTime,0);

                        

                        }

			self::halt('MySQL Query Error', $sql);

		}

		if(D_BUG) {

                       // sleep(1);

			$mtime = explode(' ', microtime());

			$sqlendttime =  $mtime[1] + $mtime[0]  ;

			$sqlQueryTime = number_format($sqlendttime - $sqlstarttime,6);

                        dblogs($sql, $sqlQueryTime,1);

			$explain = array();

			$info = mysql_info();

			if($query && preg_match("/^(select )/i", $sql)) {

				$explain = mysql_fetch_assoc(mysql_query('EXPLAIN '.$sql, self::$link));

			}

			$GLOBALS['mysql_debug_query'][] = array('sql'=>$sql, 'time'=>$sqlQueryTime, 'info'=>$info, 'explain'=>$explain);

		}

		self::$querynum++;

		return $query;

	}



	static function affected_rows() {

		return mysql_affected_rows(self::$link);

	}



	static function error() {

		return ((self::$link) ? mysql_error(self::$link) : mysql_error());

	}



	static function errno() {

		return intval((self::$link) ? mysql_errno(self::$link) : mysql_errno());

	}



	static function result($query, $row) {

		$query = @mysql_result($query, $row);

		return $query;

	}



	static function num_rows($query) {

		$query = mysql_num_rows($query);

		return $query;

	}



	static function num_fields($query) {

		return mysql_num_fields($query);

	}



	static function free_result($query) {

		return mysql_free_result($query);

	}



	static function insert_id() {

		return ($id = mysql_insert_id(self::$link)) >= 0 ? $id : self::result(self::query("SELECT last_insert_id()"), 0);

	}



	static function fetch_row($query) {

		$query = mysql_fetch_row($query);

		return $query;

	}



	static function fetch_fields($query) {

		return mysql_fetch_field($query);

	}



	static function version() {

		return mysql_get_server_info(self::$link);

	}



	static function close() {

		return mysql_close(self::$link);

	}



	static function halt($message = '', $sql = '') {

		$dberror = self::error();

		$dberrno = self::errno();

		

		echo "<div style=\"position:absolute;font-size:11px;font-family:verdana,arial;background:#EBEBEB;padding:0.5em;\">

				<b>MySQL Error</b><br>

				<b>Message</b>: $message<br>

				<b>SQL</b>: $sql<br>

				<b>Error</b>: $dberror<br>

				<b>Errno.</b>: $dberrno<br>

				</div>";

		exit();

	}

        static function  getQueryNum()

        {

            return self::$querynum;

        }

        static function getTableInfo($tableName)

        {

            

            $ColumnDetail=self::query("select * from $tableName limit 1 ");

            //echo "select * from $tableName limit 1";

            $num=mysql_num_fields($ColumnDetail);

 

            echo '<table width="472" height="80" border="1" cellpadding="0" cellspacing="0"  

                style="border-collapse:collapse; color:#369" bordercolordark="#000" bordercolorlight="#000000">';

           

              for($i=0;$i<$num;$i++)

            {

               echo '<tr>

                    <td width="80">'.mysql_field_name($ColumnDetail,$i).'</td>

                    <td width="386">'.mysql_field_type($ColumnDetail,$i)." ". mysql_field_flags($ColumnDetail,$i)." ".mysql_field_len($ColumnDetail,$i).'</td>

                  </tr>';

             }

           echo '</table>';

            

            

            



            

        }

     

}



?>

 3 index.php

<?php

require_once './common.inc.php';

@header('Content-type: text/html;charset=UTF-8');



//$nextWeek = time() + (7 * 24 * 60 * 60);

//                   // 7 days; 24 hours; 60 mins; 60secs

//echo 'Now:       '. date('Y-m-d') ."\n";

//echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";



MysqlHelper::$charset = 'utf8';

MysqlHelper::connect($dbhost, $dbuser, $dbpw, $dbname );

$query=MysqlHelper::query("SELECT id,name,concat(catpath,id,'-') as abspath FROM categorys where id<>1 order by abspath");



$categoryArr=array();





 while ($rs = MysqlHelper::fetch_array($query)){

                            $categoryArr[$rs['id']] = $rs;

 }

 

$option="";

$tmp_selected="";//是否选中

foreach($categoryArr as $row){

     //echo count ( explode ( '-', $row ['catpath'] ) );

     $space = str_repeat ( '  ', count ( explode ( '-', $row ['abspath'] ) ) );

   

       $tmp_selected=(isset($_GET['cateid']) && $_GET['cateid']== $row ['id'])?"selected='selected'":"";



     $option .= '<option value="' . $row ['id'] . '"'. $tmp_selected.' >' . $space . $row ['name'] . '</option>';

 }

 unset($tmp_selected);



 

 

print <<<EOF

 <select name="cateid">

$option

</select>

EOF

 



?>

 



<?php

  require_once './foot.php';



?>

 4 生成的日志

    2011-10-31 16:16:41 ok connection to Mysql[localhost]  [3.241 毫秒]

    2011-10-31 16:16:41 ok Mysql switch to db[tt]  [0.787 毫秒]

    2011-10-31 16:16:41 ok SELECT id,name,concat(catpath,id,'-') as abspath FROM categorys where id<>1 order by abspath  [1.066 毫秒]

    2011-10-31 16:16:41 ok connection to Mysql[localhost]  [1.78 毫秒]

    2011-10-31 16:16:41 ok Mysql switch to db[tt]  [0.373 毫秒]

    2011-10-31 16:16:41 ok SELECT id,name,concat(catpath,id,'-') as abspath FROM categorys where id<>1 order by abspath  [0.782 毫秒]

    2011-10-31 16:16:41 ok connection to Mysql[localhost]  [1.964 毫秒]

    2011-10-31 16:16:41 ok Mysql switch to db[tt]  [0.531 毫秒]

    2011-10-31 16:16:41 ok SELECT id,name,concat(catpath,id,'-') as abspath FROM categorys where id<>1 order by abspath  [0.648 毫秒]

 

你可能感兴趣的:(mysql)