Bài giảng Phát triển phần mềm nguồn mở - Bài 10 - Nguyễn Hữu Thể
PHÁT TRIỂN PHẦN MỀM NGUỒN MỞ
DATABASE, MIGRATIONS & SEEDING
Nguyễn Hữu Thể
Giới thiệu
− Laravel kết nối tới các database và thực thi các query
với nhiều database back-ends thông qua sử dụng
• raw SQL,
− Hiện tại, Laravel hỗ trợ sẵn 4 database:
• MySQL
• Postgres
• SQLite
• SQL Server
3
Cấu hình
− Thư mục config/database.php.
• Trong file này: có thể định nghĩa tất cả các kết nối cơ sở dữ liệu, cũng
như chỉ định connection nào là mặc định.
❖ Cấu hình SQL Server
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
],
4
Đọc & ghi các kết nối
'mysql' => [
'read' => [
'host' => '192.168.1.1',
],
'write' => [
'host' => '196.168.1.2'
],
'driver'
=> 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'
=> '',
],
5
Thiết lập database trong file cấu hình chung .env
(Tên_Project/.env)
APP_ENV=local
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
APP_KEY=base64:SPqqJfE1ADzonR
ot2o5g9J8Ix3iRVHsFOclr0KC1KHI=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
DB_DATABASE=ten_database
DB_USERNAME=root
DB_PASSWORD=
PUSHER_APP_ID=
PUSHER_KEY=
PUSHER_SECRET=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
6
Thực thi lệnh select
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function index()
{
$users = DB::select('select * from users where active = ?', [1]);
return view('user.index', ['users' => $users]);
}
}
Có thể thực thi câu query sử dụng liên kết đặt tên:
$results = DB::select('select * from users where id = :id', ['id' => 1]);
7
Thực thi lệnh select
Syntax
array select(string $query, array $bindings = array())
•$query(string) – query to execute in database
•$bindings(array) – values to bind with queries
Parameters
Returns
array
Description
Run a select statement against the database.
8
Thực thi câu lệnh insert
− Hàm insert nhận câu raw SQL query ở tham số đầu
tiên, và bindings ở tham số thứ hai
DB::insert('insert into users (id, name) values (?, ?)', [1, ‘Tom']);
Syntax
bool insert(string $query, array $bindings = array())
•$query(string) – query to execute in database
•$bindings(array) – values to bind with queries
Parameters
Returns
bool
Description
Run an insert statement against the database.
9
Thực thi câu lệnh update
− Hàm update: update các records đang có trong cơ sở
dữ liệu. Số lượng row ảnh hưởng bởi câu lệnh sẽ
được trả về qua hàm này
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
Syntax
int update(string $query, array $bindings = array())
•$query(string) – query to execute in database
•$bindings(array) – values to bind with queries
Parameters
Returns
int
Description
Run an update statement against the database.
10
Thực thi câu lệnh delete
− Hàm delete: xoá các records khỏi cơ sở dữ liệu.
Giống như update, số lượng dòng bị xoá sẽ được trả
về
$deleted = DB::delete('delete from users');
Syntax
int delete(string $query, array $bindings = array())
•$query(string) – query to execute in database
•$bindings(array) – values to bind with queries
Parameters
Returns
int
Description
Run a delete statement against the database.
11
Thực thi một câu lệnh chung
− Một vài câu lệnh cơ sở dữ liệu không trả về giá trị gì
cả. Với những thao tác kiểu này, có thể sử dụng hàm
statement trong DB facade
DB::statement('drop table users');
12
Database Example
− Table student
Column Name Column Datatype
Extra
Id
int(11)
varchar(25)
Primary key | Auto increment
Name
− We will see how to add, delete, update and retrieve
records from database using Laravel in student table.
13
Database Example - insert
− Step 1 − Execute the below command to create a controller
called StudInsertController
php artisan make:controller StudInsertController
14
Step 2 − Code file app/Http/Controllers/StudInsertController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StudInsertController extends Controller {
public function insertform(){
return view('stud_create');
}
public function insert(Request $request){
$name = $request->input('stud_name');
DB::insert('insert into student (name) values(?)',[$name]);
echo "Record inserted successfully.<br/>";
echo '<a href = “../insert">Click Here</a> to go back.';
}
}
15
Step 3 − Create a view file resources/views/stud_create.php
<html>
<head>
<title>Student Management | Add</title>
</head>
<body>
<form action="./create" method="post">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<table>
<tr>
<td>Name</td><td><input type='text' name='stud_name' /></td>
</tr>
<tr>
<td colspan='2'><input type='submit' value="Add student" /></td>
</tr>
</table>
</form>
</body>
</html>
16
Step 4 − Add the following lines in routes\web.php
Route::get('insert','StudInsertController@insertform');
Route::post('create','StudInsertController@insert');
Step 5 − Visit the following URL to insert record in database.
17
Database Example - Update
− Step 1 − Execute the below command to create a controller
called StudViewController.
php artisan make:controller StudUpdateController
18
Step 2 − Code file app/Http/Controllers/ StudUpdateController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StudUpdateController extends Controller {
public function index(){
$users = DB::select('select * from student');
return view('stud_edit_view',['users'=>$users]);
}
public function show($id) {
$users = DB::select('select * from student where id = ?',[$id]);
return view('stud_update',['users'=>$users]);
}
public function edit(Request $request,$id) {
$name = $request->input('stud_name');
DB::update('update student set name = ? where id = ?',[$name,$id]);
echo "Record updated successfully.<br/>";
echo '<a href = "../edit-records">Click Here</a> to go back.';
}
}
Step 3 − Create a view resources/views/stud_edit_view.blade.php
<html>
<head>
<title>View Student Records</title>
</head>
<body>
<table border = "1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Edit</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td><a href = 'edit/{{ $user->id }}'>Edit</a></td>
</tr>
@endforeach
</table>
</body>
</html>
Tải về để xem bản đầy đủ
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Phát triển phần mềm nguồn mở - Bài 10 - Nguyễn Hữu Thể", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
File đính kèm:
bai_giang_phat_trien_phan_mem_nguon_mo_bai_10_nguyen_huu_the.pdf

