search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

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

此篇文章瀏覽量: 3,180

繁體中文:

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;
});

若覺得文章有幫助,請多分享,讓其他同好也能吸收網站技能知識。



熱門推薦

本文由 carlos-studiocom 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦