thinkphp5 dbÀàÔõôʹÓÃ
Ò»¡¢ÅþÁ¬Êý¾Ý¿â
ÅþÁ¬Êý¾Ý¿âÓÐÁ½ÖÖ·½·¨£¬Ò»ÖÖÊÇÔÚconfig.phpÖÐÉèÖã¬ÁíÒ»ÖÖÊÇÔÚʵÀý»¯DbÀàʱ´«ÈëÅþÁ¬²ÎÊý¡£
ÔÚconfig.phpÖÐÉèÖãº
return [ // Êý¾Ý¿âÀàÐÍ 'type' => 'mysql', // ЧÀÍÆ÷µØµã 'hostname' => '127.0.0.1', // Êý¾Ý¿âÃû 'database' => 'test', // Êý¾Ý¿âÓû§Ãû 'username' => 'root', // Êý¾Ý¿âÃÜÂë 'password' => '', // Êý¾Ý¿âÅþÁ¬¶Ë¿Ú 'hostport' => '', ];
µÇ¼ºó¸´ÖÆ
ʵÀý»¯DbÀàʱ´«ÈëÅþÁ¬²ÎÊý£º
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
use think\Db; $config = [ // Êý¾Ý¿âÀàÐÍ 'type' => 'mysql', // ЧÀÍÆ÷µØµã 'hostname' => '127.0.0.1', // Êý¾Ý¿âÃû 'database' => 'test', // Êý¾Ý¿âÓû§Ãû 'username' => 'root', // Êý¾Ý¿âÃÜÂë 'password' => '', // Êý¾Ý¿âÅþÁ¬¶Ë¿Ú 'hostport' => '', ]; Db::connect($config);
µÇ¼ºó¸´ÖÆ
¶þ¡¢»ù±¾²Ù×÷
1.ÅÌÎʲÙ×÷
use think\Db; //ÅÌÎÊÒ»ÌõÊý¾Ý Db::table('user')->where('id', 1)->find(); //ÅÌÎʶàÌõÊý¾Ý Db::table('user')->where('age', '>', 18)->select();
µÇ¼ºó¸´ÖÆ
2.²åÈë²Ù×÷
use think\Db; $data = [ 'username' => 'admin', 'password' => md5('admin'), 'sex' => 1, 'age' => 20, ]; Db::table('user')->insert($data);
µÇ¼ºó¸´ÖÆ
3.¸üвÙ×÷
use think\Db; Db::table('user')->where('id', 1)->update(['age' => 21]);
µÇ¼ºó¸´ÖÆ
4.ɾ³ý²Ù×÷
use think\Db; Db::table('user')->where('id', 1)->delete();
µÇ¼ºó¸´ÖÆ
Èý¡¢¸ß¼¶²Ù×÷
1.Á´Ê½²Ù×÷
Á´Ê½²Ù×÷¿ÉÒÔ¼ò»¯sqlÓï¾äµÄÌÜд¡£
use think\Db; Db::table('user') ->alias('u') ->join('role r', 'u.role_id=r.id') ->where('u.id', 1) ->field('u.username, r.name') ->find();
µÇ¼ºó¸´ÖÆ
2.µ÷ÊÔÒªÁì
ÔÚ¿ª·¢ÇéÐÎÖУ¬ÎÒÃǾ³£ÐèÒªÉó²ésqlÓï¾äµÄÖ´ÐÐÇéÐΣ¬DbÀàÌṩÁËÈý¸öµ÷ÊÔÒªÁ죺getLastSql¡¢getExplainºÍgetSqlLog¡£
use think\Db; Db::table('user')->getLastSql(); Db::table('user')->where('age', '>', 18)->getExplain(); Db::table('user')->where('age', '>', 18)->select(); Db::table('user')->getLastSql(); print_r(Db::getSqlLog());
µÇ¼ºó¸´ÖÆ
getLastSqlÒªÁì¿ÉÒÔ»ñÈ¡×îºóÒ»´ÎÖ´ÐеÄsqlÓï¾ä¡£
getExplainÒªÁì¿ÉÒÔ»ñÈ¡sqlÓï¾äµÄÖ´ÐÐÍýÏë¡£
getSqlLogÒªÁì¿ÉÒÔ»ñÈ¡ËùÓÐÖ´ÐеÄsqlÓï¾äºÍÖ´ÐÐʱ¼ä¡£
ÒÔÉϾÍÊÇthinkphp5 dbÀàÔõôʹÓõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡