ホームページ  >  記事  >  バックエンド開発  >  PHP は mysql データベース操作クラスを実装します。共有_PHP チュートリアル

PHP は mysql データベース操作クラスを実装します。共有_PHP チュートリアル

WBOY
WBOYオリジナル
2016-07-13 10:24:56828ブラウズ

コードをコピーします コードは次のとおりです:

/*
データベース操作クラス
*/
class Mysql{
private $LocalHost = 'localhost';
private $LoaclUser = 'root';
private $LocalPass = '123456';
private $ LocalBase = 'jiangxibaiyi';
private $LocalCode = 'UTF8';
private $PreFix;
private $Conn;
private $Start = 0;
private $Error = false; //データベース接続ステータス、false は接続されていないことを意味します。接続が異常です
public $Err = true; //SQL 実行結果

private $Table;
private $Field = '*';
private $Where = '';
private $Order = '';

private $ PageSize = 0; //ページ表示->ページごとのアイテム数、0 はページング表示なしを意味します
private $PageCount = 1; //ページ表示->合計アイテム数
private $PageNum = 1; /ページ表示 ->合計ページ数
private $PageNo = 1; //ページング表示 ->現在のページは何ですか
private $PageKey = 'page' //ページング URL パラメーター キー
PageStart = 0; //ページング表示 -> 現在返される項目はどれですか? private $Select;
private $Rest;

private $Result = false;//result set

public $FormArray = array();

public $Instr_ID = 0;
private $j = 0;


public function Parameter($Loca, $Root, $Pass, $Base, $Code, $PreFix = ''){
$this->LoaclUser = $Root;
$this->LocalBase = $Base;
$this->LocalCode = $Code;
$this->LocalHost = $Loca;
$this->LocalPass = $Pass;
$ this->PreFix = $PreFix;
return $this;
}
プライベート関数 Connection( $Sql ){
!function_exists(mysqli_connect) ? die('クエリが失敗しました、mysqli 拡張機能をロードできません') : null;
$ this->Conn = @new mysqli( $this->LocalHost, $this->LoaclUser, $this->LocalPass, $this->LocalBase);
$this->Error = mysqli_connect_errno() == 0 ? true : false;
!$this->Error ? die('データベース接続エラー。データベース接続パラメータを確認してください') : null;
!$this->Conn->query('SET名前 ' . $this->gt;LocalCode);
$this->Rest = $this->Conn->query($Sql);
$this->Err = mysqli_error($this->Conn) );
$this->Instr_ID = mysqli_insert_id($this->Conn);
$this->Rest->free_result;
$this->Conn->close;
$this -> FormArray = '';
return $this;
}

public function null(){
$this->gt;PageSize = 0;
//$this->PageCount = 1;
$this->PageStart = 1;
$this->フィールド = ' * ';
$this->選択 = '';
unset($this->テーブル, $this->Where,$this->順序, $ this->Result);
}

public function Table( $TableName ) {//データ テーブル
$this ->null();
$this->Table = '`' 。 PreFix . '` ';
return $this;
}

public function Field( $Array = '*' ) {//Data フィールド
!empty( $this->Field ) ? ;Field = '' : null ;
$Array =explode(',', $Array);
foreach ( $Array as $field ) {
$this->Field .= !$this->Start ? `' . $field . ' `' : ', `' . $this->Start++;
}
$this->Start = 0;
return $this;
}

public function Where( $Where ) {//Condition
$this->Where = ' where ' .$Where;
return $this; by ' 。 k ( $key ) {//ページング URL パラメータ key
$this->PageKey = $key;
return $this;
}

public function Page( $PageSize ) {//分页
$this->PageSize = $PageSize;
$this->PageNo = $this->get( $this->PageKey );
$this ->ページ番号 = empty( $this->ページ番号 ) || !isset( $this->ページ番号 ) || !is_numeric( $this->ページ番号 ) || $this->ページ番号 < 1? 1 : $this->PageNo;
return $this;
}

public function post( $Key, $Filter = true ){
return $Filter ? trip_tags($_POST[$Key]) : $_POST[$Key];
}

public function get( $Key, $Filter = true ){
return $Filter ? trip_tags($_GET[$Key]) : $_GET[$Key];
}

public function Sel(){
$this->Select = 'Select ' 。 $this->フィールド 。 ' から ' 。 $this->テーブル 。 $this->どこ . $this->Order;
$this->Connection( $this->Select );
if ( $this->Rest->num_rows ) {
while ( $Rs = $this->Rest ->fetch_assoc() ) {
$this->Result[] = $Rs;
}
}
$DataBase = $this->Result;
return empty($DataBase) ? false : $DataBase;
}

public function querys( $Sql = '', $Type = 'not', $biao = false ) {
$this->Select = $Sql;
$this->Connection ( $this->Select );
if ( $this->Rest->num_rows ) {
if ( !$biao ) {
while ( $Rs = $this->Rest->fetch_array() ) {
$this->Result[] = !preg_match('/^d+$/i', $Type) ?  $Rs : $Rs[ $Type ];
}
} else {
while ( $Rs = $this->Rest->fetch_assoc() ) {
$this->Result[] = $Rs;
}
}
}
$DataBase = $this->Result;
return empty($DataBase) ? false : $DataBase;

}

パブリック関数が実行されます( $Sql = '' ){
$this->Connection( $Sql );
return $this->Rest;
}


パブリック関数が存在します( $T = '', $F = '', $W = ''){
if ( empty( $F ) ) { return 0; }
$cmd = 空( $W ) ? ' sum(' . $F . ') を `baiyinum` として `' から選択します。 $this->PreFix 。 $T .'`' : 'sum(' . $F . ') を `baiyinum` として `' から選択します。 $this->PreFix 。 $T .'' ここで ' . $W;
$this->Connection( $cmd );
unset( $T, $F, $W, $cmd );
$Rel = $this->>Rest->fetch_array();
return Round( $Rel['baiyinum'], 2 );
}


public function ExistsTo( $Bili = 10000, $T = '', $F = '', $W = ''){
if ( empty ( $F ) ) { 0 を返します。 }
$cmd = 空( $W ) ? ' sum(' . $F . ') を `baiyinum` として `' から選択します。 $this->PreFix 。 $T .'`' : 'sum(' . $F . ') を `baiyinum` として `' から選択します。 $this->PreFix 。 $T .'' ここで ' . $W;
$this->Connection( $cmd );
unset( $T, $F, $W, $cmd );
$Rel = $this->>Rest->fetch_array();
return round( $Rel['baiyinum'] * $Bili );
}


public function Select( $Type = true, $ListNum = 1 ){ // 返记录(数组形式、返条数)
$this- >選択 = '選択' 。 $this->フィールド 。 ' から ' 。 $this->テーブル 。 $this->どこ . $this->Order;
if ( is_numeric( $ListNum ) ) {
if ( $this->PageSize > 0 ) {
$this->Connection( $this->Select );//执行查询
$this->PageCount = $this->Rest->num_rows;//记录总数を取得
$this->PageNum = ceil($this->PageCount / $this->PageSize); //总共有量页
$this->PageNo = $this->PageNo > $this->ページ番号 ? $this->PageNum : $this->PageNo;
$this->PageStart = ( $this->PageNo - 1 ) * $this->PageSize;   //当前从第几条开始返
$this->Select .= 'limit' 。 $this->PageStart 。 ', ' .$this->PageSize; // 重新构造句sql语
} else {
$this->Select .= 'limit' . $ListNum; // 重新构造句sql语
}
} else {
   $this->Select   .= ' limit 1'; //重新构造sql语句
   }
   //echo $this->Select;
   $this->Connection( $this->Select );//再次执行查询
   if ( $this->Rest->num_rows ) {//如果记录存在
  if ( $Type ) {
    while ( $Rs = $this->Rest->fetch_array() ) {
     $this->Result[] = $Rs;
    }
  }else{
    while ( $Rs = $this->Rest->fetch_assoc() ) {
     $this->Result[] = $Rs;
    }
  }
   }
   if ( ( $ListNum == 1 or !is_numeric( $ListNum ) ) && !$this->PageSize) { $this->Result = $this->Result[0]; }
   $DataBase = $this->Result;
   return empty($DataBase) ? false : $DataBase;
 }

   public function Num() { //返回记录总数
     $this->Select = 'Select ' . $this->Field . ' from ' . $this->Table . $this->Where . $this->Order;
  $this->Connection( $this->Select );//执行查询
  return $this->Rest->num_rows;//取得记录总数
   }

   public function PageNav($NumNav = false ) {  //分页
  $Action = $this -> get('action');
  !empty( $Action ) or $Action =  'index';
  $Module = $this -> get('module');
  !empty( $Module ) or $Module = 'index';
  $NavUrl   = '/' . $Module . '/' . $Action . '/' . $this -> PageKey .'/';
  $NaIndex  = '/' . $Module . '/' . $Action;
  $PageHtml = "\n
";
  $PageHtml .= '' . $this->PageCount . '条记录        ' . $this->PageNo . '/' . $this->PageNum . '页            ';
  $this->PageNo <= 1 or $PageHtml .= "首页\nPageNo - 1) . "\">上一页\n";
 if ( $NumNav ) { $PageHtml .= $this->NumPage($NavUrl); }
 $this->PageNo >= $this->PageNum or $PageHtml .= "PageNo + 1) .  "\">下一页\nPageNum . "\">尾页\n";
 $PageHtml .= "
\n";
 return  $PageHtml;
   }

   private function NumPage( $Can = '' ) { //数字分页
    $NumHtml = '';
    $First   = 1;
    $Last    = $this->PageNum;
    if ( $this->PageNum > 5 ) {
     if ( $this->PageNo < $this->PageNum ) {
     $First = $this->PageNo - 2;
     $Last  = $this->PageNo + 2;
     }else{
     $First = $this->PageNo - 4;
     $Last  = $this->PageNum;
     }
    }
    if ( $First < 1 ) { $First = 1; $Last = $First + 4;}
if ( $Last > $this->PageNum ) { $First   = $this->PageNum - 4; $Last = $this->PageNum;}
    for( $i = $First; $i <= $Last; $i++) {
$NumHtml .= $this->PageNo != $i ? "\n\t" . '' . $i . '' . "\n\t" : "\n\t" .'' . $i . '' . "\n\t";
    }
    unset($Can, $First, $i, $Last);
    return $NumHtml;
   }

   public function UserPage($NumNav = false, $PageName = 'index', $Mulu = 'user' ) {  //会员中心分页
     $NavUrl   = '/' . $Mulu . '/' . $PageName . '/' . $this->PageKey . '/';
  $PageHtml = "\n
";
  $PageHtml .= '' . $this->PageCount . '条记录        ' . $this->PageNo . '/' . $this->PageNum . '页            ';
  $this->PageNo <= 1 or $PageHtml .= "首页\nPageNo - 1) . "\">上一页\n";
 if ( $NumNav ) { $PageHtml .= $this->NumPage($NavUrl); }
 $this->PageNo >= $this->PageNum or $PageHtml .= "PageNo + 1) .  "\">下一页\nPageNum . "\">尾页\n";
 $PageHtml .= "
\n";
 return  $PageHtml;
   }

  
   //表单处理开始

 //判断表单时候提交
 public function FormIs( $Keys = 'mm' ) {
  return $_POST[ $Keys ] == 1 ? true : false;
 }

 //post方式获取数据
 public function _post( $Keys = '', $TiHuan = '') {
  $Values = strip_tags( $_POST[ $Keys ] );
  $this->FormArray[$Keys] = empty( $Values ) ? $TiHuan : $Values;
        return  empty( $Values ) ? $TiHuan : $Values;
 }

 //get方法获取数据
 public function _get( $Keys = '', $TiHuan = '') {
  $Values = strip_tags( $_GET[ $Keys ] );
        return  empty( $Values ) ? $TiHuan : $Values;
 }

 //判断是否为数字并且不小于0
 public function IsNum( $Num = 0, $Mesg = '参数必须为数字' ) {
  if ( is_numeric( $Num ) && !empty( $Num ) && $Num >= 0 ) {
   return $Num;
  }else{
   die( $Mesg );
  }
 }

 //判断是否为数字并且不小于0返回True/False
 public function NumBer( $Num = 0) {
   return  is_numeric( $Num ) && !empty( $Num ) && $Num >= 0 ? true : false;
 }

 //检测相关数据似乎存在
 public function IsData($Types = true, $memg = '数据已经存在' ){
  $this->Connection('select ' . $this->Field . ' from ' . $this->Table . $this->Where);
  if ( $Types ){
   $this->Rest->num_rows > 0 ? die( $memg ) : null;
  } else {
   return $this->Rest->num_rows;
  }
 }

 
 //写入数据库记录
 public function into( $Mesg = '' ){
  !is_array( $this->FormArray ) ? die( $Mesg ) : null;
  $Sql = 'insert into ' . $this->Table . ' (`';
  $I   = 0;
  foreach ( $this->FormArray as $Key => $Val ){
   $Duan .= !$I ? $Key . '`' : ', `' . $Key . '`';
   if ( is_numeric( $Val ) ){
    $Vals .= !$I ? $Val : ', ' . $Val;
   }else{
    $Vals .= !$I ? '\'' . $Val . '\'' : ', \'' . $Val . '\'';
   }
   $I++;
  }
  $Sql .= $Duan . ') values (' . $Vals . ')';

  //@file_put_contents('1.sql', $Sql, FILE_APPEND);

  $this->Connection( $Sql );
  return !empty( $this->Err ) ? false : true;
 }

   //数组形式写入数据
   public function MsgBox( $Table = '', $Filed = array() ) {
    $this -> Table($Table);
    foreach( $Filed as $Key => $Val ) {
    $this -> FormArray[ $Key ] = $Val;
    }
   return $this ->  Into('未取得数据');
   }

   //修改数据库记录
   public function Edit( $Array = array() ) {
    if ( empty( $Array ) ) { $Array = $this -> FormArray; }
    if ( !is_array( $Array ) || empty( $Array ) ) {
     return false;
    } else {
       $Sql = 'update ' . $this -> Table . ' set ';
    $I   = 0;
    $Sub = '';
    $Huan = array('-' => '[jian]', '+' => '[jia]', '*' => '[cheng]', '/' => '[chu]');
    $Zhan = array('[jian]' => '-', '[jia]' => '+', '[cheng]' => '*', '[chu]' => '/');

foreach ( $Array as $Files => $Val ) {
$Val = !is_numeric( $Val ) && !preg_match('/`w+`s*(+|-|*|/)/i', $ヴァル)? 「」。 $Val 。 '' : $Val;
foreach ( $Huan as $key => $val ){
$Val = str_replace($key, $val, $Val);
}
$duan = !$I ? 「」。 $Files 。 '` = ' : '、 ' 。 $Files 。 '` = ';
$Sub .= $duan 。 $Val;
$I++;
}
$Sql .= $Sub 。 $this -> Where;
foreach ( $Zhan as $Fan => $Hui ) {
$Sql = str_replace($Fan, $Hui, $Sql);
}

//echo $Sql;死ぬ;

$this -> Connection( $Sql );
unset( $Array, $duan, $Fan, $Files, $Huan, $Hui, $I, $key, $Sql, $Sub, $Val, $Zhan, $val );
return !empty( $this -> エラー ) ? false : true;
}
}

//删除数据库记录
public function del(){
$Sql = 'から削除します。 $this->テーブル 。 $this->Where;
$this->Connection( $Sql );
unset($Sql);
return !empty( $this->Err ) ? false : true;
}

//表单处理结束

//页面跳转
public function Msg( $Text = '操作成功' ) {
echo '';
echo '';
exit;
}

# 取得系统当前時刻间
public function Times(){
return str_replace('-', '[jian]', date('Y-m-d H:i:s '));
}

# 取得用户IP地址
public function GetIP(){
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv( "HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "不明";
return($ip);
}


//最終关闭数据库连接
public function Close(){
!is_object( $this -> Conn ) または mysqli_close( $this -> Conn );
}

}

使用方法:
マニュアルデータ库对オブジェクト
$Conn = new Mysql;
追加データ库パラメータ
$Conn->Parameter(データ库サービス器, データ库用户名, データ库密コード, データ库名, データ库编コード, データ库表前缀[可空] ]);

上の代償はこの種類のファイルをすでに追加しており、いくつかのデータセット接続パラメータを初期化しています!

次の介绍几个基本的方法関数:

1、 $Conn -> Table();
データテーブルを選択、パラメータはデータテーブル名
2、$Conn -> Field();
選択されたフィールド名、複数の使用する番号間隔、この方法を使用しない場合、すべて
3、$Conn -> が返されます。 Where();
句Sql Where子の语、条件に応じて
4、$Conn -> Order();
Sql排序
5、$Conn -> Page(int);
パラメータは、この方法を使用する場合のように、正整数です
6、$Conn -> Select(布尔值);
実行、返される数集合、ある場合、それは 2 つの数組です、ない場合、返される、パラメータは省略可能、省略される場合、真である、返される数集合には数字の要素が含まれます
7 、$Conn -> Del();
删除记录
8、 $Conn -> Edit(array());
修正修正记录、パラメータは一組の数組、数組键はフィールド名、数組はフィールド值
9、$Conn -> Into(array());
パラメータを 1 つのグループ、数値グループ名をフィールド名、数値グループをフィールドに追加します。
上記の方法は継続的に使用できます。


$Rult = $Conn -> Table('user') -> Select(); // クエリはユーザー テーブル内のすべてのレコードを返します
$Rult = $Conn -> > Page(20) -> Select();// クエリはユーザー テーブル内のすべてのレコードを返し、ページごとに 20 レコードを表示します。


http://www.bkjia.com/PHPjc/825254.html

www.bkjia.comtru​​ehttp://www.bkjia.com/PHPjc/825254.html技術記事次のようにコードをコピーします: ?php /* データベース操作クラス*/ class Mysql{ private $LocalHost = 'localhost'; private $LoaclUser = 'root';
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。