0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Laravel sql]DB:selectの中身のSQL文のプレースホルダの使い方メモ

Posted at

#状況
Laravel入門でDBクラスを使った際にプレースホルダの例が乗っていたので使えそうなのでメモ

##controller

use Illuminate\Support\Facades\DB;  //DBクラスのnamespaceを指定

public function index(Request $request)
{
  if (isset($request->id)) 
  {
    $param = ['id' => $request->id]; //プレースホルダ用に連想配列を作る
    $items = DB::select('select + from people where id = :id', $param);
  } else {
    $items = DB::select('select * from people');
  }
  return view('hello.index', ['items' => $items]);
}

selectメソッドの第一引数のsql文の中で:idと置いて置いて
第二引数に連想配列を代入すると:idに一致するキーを連想配列から取得してくれるようだ。
?id=数字のクエリ文字を入れてアクセスすると望みの動きをする。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?