2017年9月26日 星期二

Laravel,插入資料,讀取資料,更新資料,刪除資料


/*檔案:routes/web.php*/
Route::get('/insert', function () {
DB::insert('insert into posts(title, content) values(?,?)',['PHP with laravel','laravel is the best thing']);
//class //static method(php oop)
});


 



瀏覽器執行:public/insert



 



/*SQL將執行*/
INSERT INTO `posts` (`id`, `title`, `content`, `created_at`, `updated_at`, `is_admin`) VALUES
(1, 'PHP with laravel', 'laravel is the best thing', NULL, NULL, 0);


 



 



 





 



 



 



 



//檔案:routes/web.php
Route::get('/read', function () {
$result=DB::select('select * from posts where id = ?',[1]);
foreach($result as $post){
return $post->title;
}
});


 



 



瀏覽器輸入public/read



呈現出編號1的文章標題



 





 



 



//檔案:routes/web.php
Route::get('/read', function () {
$result=DB::select('select * from posts where id = ?',[1]);
return $result;
});


 



瀏覽器輸入public/read



呈現出編號一這個物件的json格式



 



若return  var_dump($result)



則會用類似陣列的方式(print_r)呈現此物件



 





 



//檔案:routes/web.php
Route::get('/update', function () {
$updated=DB::update('update posts set title="新標題" where id=?',[1]);
$read=DB::select('select * from posts where id = ?',[1]);
return $read;
//如果return $updated,會印出標號,也就是1
});


瀏覽器輸入:public/update



呈現出編號1物件,並且標題已經換過





 




//檔案:routes/web.php
Route::get('/delete', function () {
$delete=DB::delete('delete from posts where id=?',[1]);
// return $deleted; 這樣會秀出1,也就是標號1
$read=DB::select('select * from posts where id =?',[1]);
return $read;
});


瀏覽器輸入:public/delete



呈現出空陣列,因為已經被刪掉了





 



沒有留言:

張貼留言