1. 安装:
    composer require illuminate/database
  2. 用法:
    <?php
    // 1. 引入包
    require_once "vendor/autoload.php";
    // 2. 使用命名空间
    use Illuminate\Database\Capsule\Manager as DB;
    // 3. 实例化对像
    $obj = new DB;
    // 4. 建立连接
    $obj->addConnection([
     'read' => [
         ['host' => 'xx.xx.xx.xx'],
         ['host' => 'xx.xx.xx.xx'],
     ],
     'write' => [
         ['host' => 'xx.xx.xx.xx']
     ],
     'driver'    => 'mysql',
     'database'  => 'test',
     'username'  => 'test_user',
     'password'  => 'test_pass',
     'charset'   => 'utf8',
     'collation' => 'utf8_unicode_ci',
     'prefix'    => '',
    ]);
    // 5. 设置全局可用
    $obj->setAsGlobal();
    // 6. 执行原生 sql 语句
    $sql_create = <<<HH
     create table if not exists users(
         id int(11) not null auto_increment primary key,
         username varchar(50) not null,
         email varchar(50) not null
     )
    HH;
    $ret_create = DB::statement($sql_create);
    // 7. 添加数据
    $insert_data = array(
     array(
         'username' => 'aaa',
         'email' => 'aaa@gmail.com'
     ),
     array(
         'username' => 'bbb',
         'email' => 'bbb@gmail.com'
     ),
     array(
         'username' => 'ccc',
         'email' => 'ccc@gmail.com'
     )
    );
    $ret_insert = $obj
             ->table('users')
             ->insert($insert_data);
    // 8. 删除数据
    $ret_delete = $obj
             ->table("users")
             ->where('id','=','3')
             ->delete();
    // 9. 更新数据
    $update_data = array(
     'username' => 'lee'
    );
    $ret_update = $obj
             ->table('users')
             ->where('id','=','2')
             ->update($update_data);
    // 10. 查询数据
    $ret_select = $obj
             ->table('users')
             ->where('id','=','2')
             ->get();
    // 11. 输出
    $ret = array(
     'ret_create' => $ret_create,
     'ret_insert' => $ret_insert,
     'ret_delete' => $ret_delete,
     'ret_update' => $ret_update,
     'ret_select' => $ret_select
    );
    var_dump($ret);
  3. 输出:
    array(5) {
    ["ret_create"]=>
    bool(true)
    ["ret_insert"]=>
    bool(true)
    ["ret_delete"]=>
    int(1)
    ["ret_update"]=>
    int(1)
    ["ret_select"]=>
    object(Illuminate\Support\Collection)#17 (1) {
     ["items":protected]=>
     array(1) {
       [0]=>
       object(stdClass)#15 (3) {
         ["id"]=>
         int(2)
         ["username"]=>
         string(3) "lee"
         ["email"]=>
         string(13) "bbb@gmail.com"
       }
     }
    }
    }
文档更新时间: 2020-11-22 20:37   作者:lee