便捷的php操作mysql库MysqliDb
2016-03-10 09:34
513 查看
github地址:https://github.com/joshcam/PHP-MySQLi-Database-Class
MysqliDb--SimpleMySQLiwrapperandobjectmapperwithpreparedstatements
Initialization
Objectsmapping
InsertQuery
UpdateQuery
SelectQuery
DeleteQuery
RunningrawSQLqueries
QueryKeywords
WhereConditions
OrderConditions
GroupConditions
PropertiesSharing
JoiningTables
Subqueries
EXISTS/NOTEXISTScondition
Hasmethod
HelperMethods
TransactionHelpers
Toutilizethisclass,firstimportMysqliDb.phpintoyourproject,andrequireit.
Itisalsopossibletoinstalllibraryviacomposer
Simpleinitializationwithutf8charsetsetbydefault:
Advancedinitialization:
tableprefix,portanddatabasecharsetparamsareoptional.Ifnocharsetshouldbesetcharset,setittonull
Alsoitispossibletoreusealreadyconnectedmysqliobject:
Ifnotableprefixweresetduringobjectcreationitspossibletosetitlaterwithaseparatecall:
IfyouneedtogetalreadycreatedmysqliDbobjectfromanotherclassorfunctionuse
dbObject.phpisanobjectmappinglibrarybuiltontopofmysqliDbtoprovidemodelrepresentationfunctionality.SeedbObjectmanualformoreinformation
Simpleexample
Insertwithfunctionsuse
Insertwithonduplicatekeyupdate
Replace()methodimplementssameAPIasinsert();
Afteranyselect/getfunctioncallsamountorreturnedrowsisstoredin$countvariable
orselectwithcustomcolumnsset.Functionsalsocouldbeused
orselectjustonerow
orselectonecolumnvalueorfunctionresult
selectonecolumnvalueorfunctionresultfrommultiplerows:
Usepaginate()insteadofget()tofetchpaginatedresult
Insteadofgettinganpurearrayofresultsitspossibletogetresultinanassociativearraywithaneededkey.Ifonly2fieldstofetchwillbesetinget(),methodwillreturnresultinarray($k=>$v)andarray($k=>array($v,$v))inrestofthecases.
MysqliDbcanreturnresultin3differentformats:ArrayofArray,ArrayofObjectsandaJsonstring.ToselectareturntypeuseArrayBuilder(),ObjectBuilder()andJsonBuilder()methods.NotethatArrayBuilder()isadefaultreturntype
Toavoidlongifcheckstherearecouplehelperfunctionstoworkwithrawqueryselectresults:
Get1rowofresults:
Get1columnvalueasastring:
Get1columnvaluefrommultiplerows:
Moreadvancedexamples:
WARNING:Inordertousecolumntocolumncomparisonsonlyrawwhereconditionsshouldbeusedascolumnnameorfunctionscantbepassedasabindvariable.
Regular==operatorwithvariables:
Regular==operatorwithcolumntocolumncomparison:
BETWEEN/NOTBETWEEN:
IN/NOTIN:
ORCASE
NULLcomparison:
Alsoyoucanuserawwhereconditions:
Orrawconditionwithvariables:
Findthetotalnumberofrowsmatched.Simplepaginationexample:
ToaddLOWPRIORITY|DELAYED|HIGHPRIORITY|IGNOREandtherestofthemysqlkeywordstoINSERT(),REPLACE(),GET(),UPDATE(),DELETE()methodorFORUPDATE|LOCKINSHAREMODEintoSELECT():
Alsoyoucanuseanarrayofkeywords:
SamewaykeywordscouldbeusedinSELECTqueriesaswell:
Optionallyyoucanusemethodchainingtocallwheremultipletimeswithoutreferencingyourobjectoveranover:
Orderbyvaluesexample:
IfyouareusingsetPrefix()functionalityandneedtousetablenamesinorderBy()methodmakesurethattablenamesareescapedwith``.
JointableproductswithtableuserswithLEFTJOINbytenantID
Itsisalsopossibletocopyproperties
Subqueryinit
Subqueryinitwithoutanaliastouseininserts/updates/whereEg.(select*fromusers)
AsubquerywithanaliasspecifiedtouseinJOINs.Eg.(select*fromusers)sq
Subqueryinselects:
Subqueryininserts:
Subqueryinjoins:
AconvenientfunctionthatreturnsTRUEifexistsatleastanelementthatsatisfythewhereconditionspecifiedcallingthe"where"methodbeforethisone.
Reconnectincasemysqlconnectiondied:
GetlastexecutedSQLquery:PleasenotethatfunctionreturnsSQLqueryonlyfordebuggingpurposesasitsexecutionmostlikelywillfailduemissingquotesaroundcharvariables.
Checkiftableexists:
mysqli_real_escape_string()wrapper:
PleasekeepinmindthattransactionsareworkingoninnoDBtables.Rollbacktransactionifinsertfails:
TotrackqueryexecutiontimesetTrace()functionshouldbecalled.
MysqliDb--SimpleMySQLiwrapperandobjectmapperwithpreparedstatements
TableofContents
Installation
Toutilizethisclass,firstimportMysqliDb.phpintoyourproject,andrequireit.require_once('MysqliDb.php');
Installationwithcomposer
Itisalsopossibletoinstalllibraryviacomposercomposerrequirejoshcam/mysqli-database-class:dev-master
Initialization
Simpleinitializationwithutf8charsetsetbydefault:$db=newMysqliDb('host','username','password','databaseName');
Advancedinitialization:
$db=newMysqliDb(Array( 'host'=>'host', 'username'=>'username', 'password'=>'password', 'db'=>'databaseName', 'port'=>3306, 'prefix'=>'my_', 'charset'=>'utf8'));
tableprefix,portanddatabasecharsetparamsareoptional.Ifnocharsetshouldbesetcharset,setittonull
Alsoitispossibletoreusealreadyconnectedmysqliobject:
$mysqli=newmysqli('host','username','password','databaseName'); $db=newMysqliDb($mysqli);
Ifnotableprefixweresetduringobjectcreationitspossibletosetitlaterwithaseparatecall:
$db->setPrefix('my_');
IfyouneedtogetalreadycreatedmysqliDbobjectfromanotherclassorfunctionuse
functioninit(){ //dbstayingprivatehere $db=newMysqliDb('host','username','password','databaseName'); } ... functionmyfunc(){ //obtaindbobjectcreatedininit() $db=MysqliDb::getInstance(); ... }
Objectsmapping
dbObject.phpisanobjectmappinglibrarybuiltontopofmysqliDbtoprovidemodelrepresentationfunctionality.SeeInsertQuery
Simpleexample$data=Array("login"=>"admin", "firstName"=>"John", "lastName"=>'Doe' ); $id=$db->insert('users',$data); if($id) echo'userwascreated.Id='.$id;
Insertwithfunctionsuse
$data=Array( 'login'=>'admin', 'active'=>true, 'firstName'=>'John', 'lastName'=>'Doe', 'password'=>$db->func('SHA1(?)',Array("secretpassword+salt")), //password=SHA1('secretpassword+salt') 'createdAt'=>$db->now(), //createdAt=NOW() 'expires'=>$db->now('+1Y') //expires=NOW()+interval1year //Supportedintervals[s]econd,[m]inute,[h]hour,[d]day,[M]onth,[Y]ear ); $id=$db->insert('users',$data); if($id) echo'userwascreated.Id='.$id; else echo'insertfailed:'.$db->getLastError();
Insertwithonduplicatekeyupdate
$data=Array("login"=>"admin", "firstName"=>"John", "lastName"=>'Doe', "createdAt"=>$db->now(), "updatedAt"=>$db->now(), ); $updateColumns=Array("updatedAt"); $lastInsertId="id"; $db->onDuplicate($updateColumns,$lastInsertId); $id=$db->insert('users',$data);
ReplaceQuery
UpdateQuery
$data=Array( 'firstName'=>'Bobby', 'lastName'=>'Tables', 'editCount'=>$db->inc(2), //editCount=editCount+2; 'active'=>$db->not() //active=!active; ); $db->where('id',1); if($db->update('users',$data)) echo$db->count.'recordswereupdated'; else echo'updatefailed:'.$db->getLastError();
update()alsosupportlimitparameter:
$db->update('users',$data,10); //Gives:UPDATEusersSET...LIMIT10
SelectQuery
Afteranyselect/getfunctioncallsamountorreturnedrowsisstoredin$countvariable$users=$db->get('users');//containsanArrayofallusers $users=$db->get('users',10);//containsanArray10users
orselectwithcustomcolumnsset.Functionsalsocouldbeused
$cols=Array("id","name","email"); $users=$db->get("users",null,$cols); if($db->count>0) foreach($usersas$user){ print_r($user); }
orselectjustonerow
$db->where("id",1); $user=$db->getOne("users"); echo$user['id']; $stats=$db->getOne("users","sum(id),count(*)ascnt"); echo"total".$stats['cnt']."usersfound";
orselectonecolumnvalueorfunctionresult
$count=$db->getValue("users","count(*)"); echo"{$count}usersfound";
selectonecolumnvalueorfunctionresultfrommultiplerows:
$logins=$db->getValue("users","login",null); //selectloginfromusers $logins=$db->getValue("users","login",5); //selectloginfromuserslimit5 foreach($loginsas$login) echo$login;
Pagination
Usepaginate()insteadofget()tofetchpaginatedresult$page=1; //setpagelimitto2resultsperpage.20bydefault $db->pageLimit=2; $products=$db->arraybuilder()->paginate("products",$page); echo"showing$pageoutof".$db->totalPages;
Resulttransformation/map
Insteadofgettinganpurearrayofresultsitspossibletogetresultinanassociativearraywithaneededkey.Ifonly2fieldstofetchwillbesetinget(),methodwillreturnresultinarray($k=>$v)andarray($k=>array($v,$v))inrestofthecases.$user=$db->map('login')->ObjectBuilder()->getOne('users','login,id'); Array ( [user1]=>1 ) $user=$db->map('login')->ObjectBuilder()->getOne('users','id,login,createdAt'); Array ( [user1]=>stdClassObject ( [id]=>1 [login]=>user1 [createdAt]=>2015-10-2222:27:53 ) )
Definingareturntype
MysqliDbcanreturnresultin3differentformats:ArrayofArray,ArrayofObjectsandaJsonstring.ToselectareturntypeuseArrayBuilder(),ObjectBuilder()andJsonBuilder()methods.NotethatArrayBuilder()isadefaultreturntype//Arrayreturntype $=$db->getOne("users"); echo$u['login']; //Objectreturntype $u=$db->ObjectBuilder()->getOne("users"); echo$u->login; //Jsonreturntype $json=$db->JsonBuilder()->getOne("users");
RunningrawSQLqueries
$users=$db->rawQuery('SELECT*fromuserswhereid>=?',Array(10)); foreach($usersas$user){ print_r($user); }
Toavoidlongifcheckstherearecouplehelperfunctionstoworkwithrawqueryselectresults:
Get1rowofresults:
$user=$db->rawQueryOne('select*fromuserswhereid=?',Array(10)); echo$user['login']; //Objectreturntype $user=$db->ObjectBuilder()->rawQueryOne('select*fromuserswhereid=?',Array(10)); echo$user->login;
Get1columnvalueasastring:
$password=$db->rawQueryValue('selectpasswordfromuserswhereid=?limit1',Array(10)); echo"Passwordis{$password}"; NOTE:forarawQueryValue()toreturnstringinsteadofanarray'limit1'shouldbeaddedtotheendofthequery.
Get1columnvaluefrommultiplerows:
$logins=$db->rawQueryValue('selectloginfromuserslimit10'); foreach($loginsas$login) echo$login;
Moreadvancedexamples:
$params=Array(1,'admin'); $users=$db->rawQuery("SELECTid,firstName,lastNameFROMusersWHEREid=?ANDlogin=?",$params); print_r($users);//containsArrayofreturnedrows //willhandleanySQLquery $params=Array(10,1,10,11,2,10); $q="( SELECTaFROMt1 WHEREa=?ANDB=? ORDERBYaLIMIT? )UNION( SELECTaFROMt2 WHEREa=?ANDB=? ORDERBYaLIMIT? )"; $resutls=$db->rawQuery($q,$params); print_r($results);//containsArrayofreturnedrows
Where/HavingMethods
where(),
orWhere(),
having()and
orHaving()methodsallowsyoutospecifywhereandhavingconditionsofthequery.Allconditionssupportedbywhere()aresupportedbyhaving()aswell.
WARNING:Inordertousecolumntocolumncomparisonsonlyrawwhereconditionsshouldbeusedascolumnnameorfunctionscantbepassedasabindvariable.
Regular==operatorwithvariables:
$db->where('id',1); $db->where('login','admin'); $results=$db->get('users'); //Gives:SELECT*FROMusersWHEREid=1ANDlogin='admin';
$db->where('id',1); $db->having('login','admin'); $results=$db->get('users'); //Gives:SELECT*FROMusersWHEREid=1HAVINGlogin='admin';
Regular==operatorwithcolumntocolumncomparison:
//WRONG $db->where('lastLogin','createdAt'); //CORRECT $db->where('lastLogin=createdAt'); $results=$db->get('users'); //Gives:SELECT*FROMusersWHERElastLogin=createdAt;
$db->where('id',50,">="); //or$db->where('id',Array('>='=>50)); $results=$db->get('users'); //Gives:SELECT*FROMusersWHEREid>=50;
BETWEEN/NOTBETWEEN:
$db->where('id',Array(4,20),'BETWEEN'); //or$db->where('id',Array('BETWEEN'=>Array(4,20))); $results=$db->get('users'); //Gives:SELECT*FROMusersWHEREidBETWEEN4AND20
IN/NOTIN:
$db->where('id',Array(1,5,27,-1,'d'),'IN'); //or$db->where('id',Array('IN'=>Array(1,5,27,-1,'d'))); $results=$db->get('users'); //Gives:SELECT*FROMusersWHEREidIN(1,5,27,-1,'d');
ORCASE
$db->where('firstName','John'); $db->orWhere('firstName','Peter'); $results=$db->get('users'); //Gives:SELECT*FROMusersWHEREfirstName='John'ORfirstName='peter'
$db->where('firstName','John'); $db->orWhere('firstName','Peter'); $results=$db->get('users'); //Gives:SELECT*FROMusersWHEREfirstName='John'ORfirstName='peter'
NULLcomparison:
$db->where("lastName",NULL,'ISNOT'); $results=$db->get("users"); //Gives:SELECT*FROMuserswherelastNameISNOTNULL
Alsoyoucanuserawwhereconditions:
$db->where("id!=companyId"); $db->where("DATE(createdAt)=DATE(lastLogin)"); $results=$db->get("users");
Orrawconditionwithvariables:
$db->where("(id=?orid=?)",Array(6,2)); $db->where("login","mike") $res=$db->get("users"); //Gives:SELECT*FROMusersWHERE(id=6orid=2)andlogin='mike';
Findthetotalnumberofrowsmatched.Simplepaginationexample:
$offset=10; $count=15; $users=$db->withTotalCount()->get('users',Array($offset,$count)); echo"Showing{$count}from{$db->totalCount}";
QueryKeywords
ToaddLOWPRIORITY|DELAYED|HIGHPRIORITY|IGNOREandtherestofthemysqlkeywordstoINSERT(),REPLACE(),GET(),UPDATE(),DELETE()methodorFORUPDATE|LOCKINSHAREMODEintoSELECT():$db->setQueryOption('LOW_PRIORITY')->insert($table,$param); //GIVES:INSERTLOW_PRIORITYINTOtable...
$db->setQueryOption('FORUPDATE')->get('users'); //GIVES:SELECT*FROMUSERSFORUPDATE;
Alsoyoucanuseanarrayofkeywords:
$db->setQueryOption(Array('LOW_PRIORITY','IGNORE'))->insert($table,$param); //GIVES:INSERTLOW_PRIORITYIGNOREINTOtable...
SamewaykeywordscouldbeusedinSELECTqueriesaswell:
$db->setQueryOption('SQL_NO_CACHE'); $db->get("users"); //GIVES:SELECTSQL_NO_CACHE*FROMUSERS;
Optionallyyoucanusemethodchainingtocallwheremultipletimeswithoutreferencingyourobjectoveranover:
$results=$db ->where('id',1) ->where('login','admin') ->get('users');
DeleteQuery
$db->where('id',1); if($db->delete('users'))echo'successfullydeleted';
Orderingmethod
$db->orderBy("id","asc"); $db->orderBy("login","Desc"); $db->orderBy("RAND()"); $results=$db->get('users'); //Gives:SELECT*FROMusersORDERBYidASC,loginDESC,RAND();
Orderbyvaluesexample:
$db->orderBy('userGroup','ASC',array('superuser','admin','users')); $db->get('users'); //Gives:SELECT*FROMusersORDERBYFIELD(userGroup,'superuser','admin','users')ASC;
IfyouareusingsetPrefix()functionalityandneedtousetablenamesinorderBy()methodmakesurethattablenamesareescapedwith``.
$db->setPrefix("t_"); $db->orderBy("users.id","asc"); $results=$db->get('users'); //WRONG:Thatwillgive:SELECT*FROMt_usersORDERBYusers.idASC; $db->setPrefix("t_"); $db->orderBy("`users`.id","asc"); $results=$db->get('users'); //CORRECT:Thatwillgive:SELECT*FROMt_usersORDERBYt_users.idASC;
Groupingmethod
$db->groupBy("name"); $results=$db->get('users'); //Gives:SELECT*FROMusersGROUPBYname;
JointableproductswithtableuserswithLEFTJOINbytenantID
JOINmethod
$db->join("usersu","p.tenantID=u.tenantID","LEFT"); $db->where("u.id",6); $products=$db->get("productsp",null,"u.name,p.productName"); print_r($products);
Propertiessharing
Itsisalsopossibletocopyproperties$db->where("agentId",10); $db->where("active",true); $customers=$db->copy(); $res=$customers->get("customers",Array(10,10)); //SELECT*FROMcustomerswhereagentId=10andactive=1limit10,10 $cnt=$db->getValue("customers","count(id)"); echo"totalrecordsfound:".$cnt; //SELECTcount(id)FROMuserswhereagentId=10andactive=1
Subqueries
SubqueryinitSubqueryinitwithoutanaliastouseininserts/updates/whereEg.(select*fromusers)
$sq=$db->subQuery(); $sq->get("users");
AsubquerywithanaliasspecifiedtouseinJOINs.Eg.(select*fromusers)sq
$sq=$db->subQuery("sq"); $sq->get("users");
Subqueryinselects:
$ids=$db->subQuery(); $ids->where("qty",2,">"); $ids->get("products",null,"userId"); $db->where("id",$ids,'in'); $res=$db->get("users"); //GivesSELECT*FROMusersWHEREidIN(SELECTuserIdFROMproductsWHEREqty>2)
Subqueryininserts:
$userIdQ=$db->subQuery(); $userIdQ->where("id",6); $userIdQ->getOne("users","name"), $data=Array( "productName"=>"testproduct", "userId"=>$userIdQ, "lastUpdated"=>$db->now() ); $id=$db->insert("products",$data); //GivesINSERTINTOPRODUCTS(productName,userId,lastUpdated)values("testproduct",(SELECTnameFROMusersWHEREid=6),NOW());
Subqueryinjoins:
$usersQ=$db->subQuery("u"); $usersQ->where("active",1); $usersQ->get("users"); $db->join($usersQ,"p.userId=u.id","LEFT"); $products=$db->get("productsp",null,"u.login,p.productName"); print_r($products); //SELECTu.login,p.productNameFROMproductspLEFTJOIN(SELECT*FROMt_usersWHEREactive=1)uonp.userId=u.id;
EXISTS/NOTEXISTScondition
$sub=$db->subQuery(); $sub->where("company",'testCompany'); $sub->get("users",null,'userId'); $db->where(null,$sub,'exists'); $products=$db->get("products"); //GivesSELECT*FROMproductsWHEREEXISTS(selectuserIdfromuserswherecompany='testCompany')
Hasmethod
AconvenientfunctionthatreturnsTRUEifexistsatleastanelementthatsatisfythewhereconditionspecifiedcallingthe"where"methodbeforethisone.$db->where("user",$user); $db->where("password",md5($password)); if($db->has("users")){ return"Youarelogged"; }else{ return"Wronguser/password"; }
Helpermethods
Reconnectincasemysqlconnectiondied:if(!$db->ping()) $db->connect()
GetlastexecutedSQLquery:PleasenotethatfunctionreturnsSQLqueryonlyfordebuggingpurposesasitsexecutionmostlikelywillfailduemissingquotesaroundcharvariables.
$db->get('users'); echo"Lastexecutedquerywas".$db->getLastQuery();
Checkiftableexists:
if($db->tableExists('users')) echo"hooray";
mysqli_real_escape_string()wrapper:
$escaped=$db->escape("'and1=1");
Transactionhelpers
PleasekeepinmindthattransactionsareworkingoninnoDBtables.Rollbacktransactionifinsertfails:$db->startTransaction(); ... if(!$db->insert('myTable',$insertData)){ //Errorwhilesaving,cancelnewrecord $db->rollback(); }else{ //OK $db->commit(); }
Queryexectutiontimebenchmarking
TotrackqueryexecutiontimesetTrace()functionshouldbecalled.$db->setTrace(true); //Asasecondparameteritispossibletodefineprefixofthepathwhichshouldbestripedfromfilename //$db->setTrace(true,$_SERVER['SERVER_ROOT']); $db->get("users"); $db->get("test"); print_r($db->trace);
[0]=>Array ( [0]=>SELECT*FROMt_usersORDERBY`id`ASC [1]=>0.0010669231414795 [2]=>MysqliDb->get()>>file"/avb/work/PHP-MySQLi-Database-Class/tests.php"line#151 ) [1]=>Array ( [0]=>SELECT*FROMt_test [1]=>0.00069189071655273 [2]=>MysqliDb->get()>>file"/avb/work/PHP-MySQLi-Database-Class/tests.php"line#152 )
相关文章推荐
- ntp时间同步服务器
- php中的魔术函数使用
- 让PHP文件每隔几秒执行一次
- PHP——explode的应用(获取字符串,拆为下拉列表)
- PHP 语句和时间函数
- PHP实现仿百度文库,豆丁在线文档效果(word,excel,ppt转flash)
- php中array_reduce和array_map的用法
- thinkphp 开发的获取用户信息
- PHP Date ( I need to use)
- 2016/3/10 PHP (超文本预处理器) 是什么?
- PHP二维码生成的方法(google APi,PHP类库,libqrencode等)
- 利用notepad++运行php
- PHP: fopen() Permission denied
- PHP实现仿百度文库,豆丁在线文档效果(word,excel,ppt转flash)
- 简单谈谈php浮点数精确运算
- PHP浮点数的一个常见问题
- Zend Framework教程之配置文件application.ini解析
- Zend Framework教程之Application和Bootstrap用法详解
- php实现无限级分类查询(递归、非递归)
- 我的PHP退役了