×ðÁú¿­Ê±¹ÙÍøµÇ¼

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ÀàÔõôʹÓõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±¹ÙÍøµÇ¼ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼ʵʱÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±¹ÙÍøµÇ¼

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
ÍøÕ¾µØͼ