laravel框架資料庫配置及操作資料庫示例
阿新 • • 發佈:2020-11-18
本文例項講述了laravel框架資料庫配置及操作資料庫。分享給大家供大家參考,具體如下:
laravel 資料庫配置
資料庫配置檔案為專案根目錄下的config/database.php
//預設資料庫為mysql 'default' => env('DB_CONNECTION', 'mysql'), 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],
發現都在呼叫env函式,找到env檔案,即根目錄下的.env檔案,
開啟修改配置引數
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret
修改為本地的資料庫資訊:
DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=123456
laravel 操作資料庫
建立student控制器,控制器程式碼
namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; class StudentController extends Controller { //新增 public function addstudent(){ $student = DB::insert('insert into student(name,age,gender) values(?,?,?)',['張三',12,2]); var_dump($student);//成功返回bloo值true } //獲取 public function getall(){ // $student = DB::select('select * from student'); $student = DB::select('select * from student where id>?',[1]); return $student;//陣列 } //修改 public function updstudent(){ $student = DB::update('update student set age= ? where name=?',[10,'張三']); var_dump($student);//成功返回bloo值true } //修改 public function delstudent(){ $student = DB::delete('delete from student where id=?',[10]); var_dump($student); } }
注意 laravel中return true會報錯:
(1/1) UnexpectedValueException
The Response content must be a string or object implementing __toString(), "boolean" given.
更多關於Laravel相關內容感興趣的讀者可檢視本站專題:《Laravel框架入門與進階教程》、《php優秀開發框架總結》、《php面向物件程式設計入門教程》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧彙總》
希望本文所述對大家基於Laravel框架的PHP程式設計有所幫助。