[Laravel] 連結MySQL資料庫 (Connect to MySQL)

繁體中文:

1、開啟app/config/database.php

// 修改相關參數
'mysql' => array(
  'driver'    => 'mysql',
  'host'      => '127.0.0.1',
  'database'  => 'learning-laravel',
  'username'  => 'root',
  'password'  => 'root',
  'charset'   => 'utf8',
  'collation' => 'utf8_unicode_ci',
  'prefix'    => '',
  'port'      => '8889',
),

2、開啟app/routes.php,測試連結的資料庫,假設已有learning-laravel資料庫,以及users資料表的存在,users資料表也有資料:

Route::get('/', function()
{
  // 測試一:取得users資料表的全部資料
  //$users = DB::table('users')->get();
  //return $users;
  
  // 測試二:取得users資料表,id為1的資料
  //$user = DB::table('users')->find(1);
  //dd($user);  // dd means: die(var_dump($user));
  //return $user->username;
  
  // 測試三:用where條件式來取得相關資料
  $users = DB::table('users')->where("username", "!=", "carlos")->get();
  //也可使用:DB::select('select * from users');
  return $users;
});

English Version:

1、Open file: app/config/database.php

// modify parameters
'mysql' => array(
  'driver'    => 'mysql',
  'host'      => '127.0.0.1',
  'database'  => 'learning-laravel',
  'username'  => 'root',
  'password'  => 'root',
  'charset'   => 'utf8',
  'collation' => 'utf8_unicode_ci',
  'prefix'    => '',
  'port'      => '8889',
),

2、Open file: “app/routes.php” to test connection of MySQL, assuming that we have learning-laravel database, and exists users table and records:

Route::get('/', function()
{
  // test 1: get all records in users table
  //$users = DB::table('users')->get();
  //return $users;
  
  // test 2: get specific id from users table
  //$user = DB::table('users')->find(1);
  //dd($user);  // dd means: die(var_dump($user));
  //return $user->username;
  
  // test 3: use where condition to get records
  $users = DB::table('users')->where("username", "!=", "carlos")->get();
  // also use:DB::select('select * from users');
  return $users;
});