# 使用Laravel進行PHP的資料庫連線 ## :memo:事前作業 請先參閱: 1.[建立Laravel框架環境](https://hackmd.io/GTD7jSI9TDuT4DUBFseMKw) ## Step.1 設定Database 首先,打開config/database.php,裡面會看到很多關於資料庫的一些設定,有些設定的內容是用env()的方式包起來的,表示這個欄位是參考.env檔裡面的設定。  再來我們打開專案裡的.env檔。  通常我們會設定的就以下幾個欄位: - DB_HOST - 資料庫的連線位置 - DB_DATABASE - 資料庫名稱 - DB_USERNAME - 使用者名稱 - DB_PASSWORD - 使用者密碼 ## Step2.建立第一個PHP 打開命令提示字元,輸入以下指令: ``` php artisan make:controller 檔案名稱 ```  這將會在app/Http/Controllers的目錄底下新增一個php的檔案,而這個檔案我們就可以利用來對資料庫進行[CRUD](https://zh.wikipedia.org/wiki/%E5%A2%9E%E5%88%AA%E6%9F%A5%E6%94%B9)(增刪查改)。 再來我們先設定路由,打開routes/web.php,在底下新增以下指令: ``` Route::get('/select_store_list', 'App\Http\Controllers\select_store_list@function1'); ```  這行程式的意思是:在網址後加上"/select_store_list"時,會呼叫App\Http\Controllers\select_store_list.php裡面的function1的方法。 接下來,我們切換到剛才建立的select_store_list.php的檔案裡,我們會看到裡面已經有一些預設好的程式碼。 ```php=1 <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class select_store_list extends Controller { // } ``` 我們需要在class外新增系統操作資料庫的類別,所以在class的上方加上以下兩行: ``` php=1 use App\Http\Requests; use Illuminate\Support\Facades\DB; ``` ### 查詢 寫下一個名叫function1的方法,並在裡面做對資料庫進行查詢的功能,所以整體的程式碼如下: ``` php=1 <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\DB; class select_store_list extends Controller { public function function1(){ $data = DB::table('store_list')->get(); dd($data); } } ``` 第13的意思是,呼叫Database的一個叫"store_list"的資料表,對其進行讀取的動作,並把資料存在$data的這個變數。 第14行的dd()則是將資料印出來的意思 。那我們在網頁上執行看看吧!  哇!可以見到資料庫裡面的東西了呢!那如果要使用WHERE語法呢?以下的程式碼都是同一個功能,請將第13行改成下列程式碼: ``` php=13 $data = DB::table('store_list')->where('ID',2)->get(); $data = DB::select('select * from store_list where ID = :id', ['id'=>2]); ``` 這行程式碼的意思等於以下的SQL語法: ``` SELECT * FROM store_list WHERE ID = 2 ``` 如果有兩個條件呢?請參考以下程式碼: ``` php=13 $data = DB::table('store_list')->where('ID',2)->where('area','建工')->get(); $data = DB::select('select * from store_list where ID = :id and area = :area', ['id'=>2, 'area'=>'建工']); ```  ## 參考資料 [Database: Getting Started - Laravel - The PHP Framework For Web Artisans](https://laravel.com/docs/8.x/database)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up