LoginSignup
0
0

More than 1 year has passed since last update.

【Php】PDOでdatabaseに接続する(3)

Posted at

初めに

PDOについて学習した内容のoutput用記事です。

※内容に間違いなどがある場合はご指摘をよろしくお願いします。
※こちらの記事はあくまでも個人で学習した内容のoutputとしての記事になります。

前回の記事:
https://qiita.com/redrabbit1104/items/2668e56d4c058221388e
https://qiita.com/redrabbit1104/items/8c5bb2b364347915a0f1

ユーザーがフォームなどを通じて入力した場合を想定

前回と同様、sql文を使ってデータベースに接続しますが、今回はユーザーがフォームからデータを入力した場合を考えます。

sql文のplace holder

ユーザーが何を入力するか分からないので、sql文のwhere句にはplace holderを利用します。place holderには2種類があり、①名前付きplace holderと②疑問符place holderがあります。

①名前付きplace holderを使う

sql文で「:」の後ろにplace holderとして使う名前を指定します。

$sql = 'select * from accounts where user_id = :id';  //名前付きplace holder

それから、sql文を実行する準備をするprepare関数を使います。戻り値はステートメントになります。

$stmt = $pdo -> prepare($sql);     //sql文を実行する準備を行う。戻り値はPDOStatement

PDOStatementのbindValue関数を使い、place holderと値を紐付けます。
3番目の引数にはPDO::PARAM_INTのように値の型を指定します。こちらはPHPで予め用意されている定数を使います。

$stmt -> bindValue('id', 4, PDO::PARAM_INT); 

紐付けの方法にはこの他にbindParam関数を使う方法もあります。

https://www.php.net/manual/ja/pdo.constants.php
最後にexecute()関数を使って実行します。

$stmt -> execute(); //実行

結果を表示させるためにfetchall()関数で該当するデータを全て取得します。

$result = $stmt -> fetchall();

連想配列という形で格納されているので、var_dump()で中身を確認できます。

var_dump($result);

スクリーンショット 2021-06-10 7.38.51.png

②疑問符place holderを使う

基本的には名前付きplace holderと同じですが、place holderとして「?」を使います。

$sql = 'select * from accounts where user_id = ?'; //疑問符place holder

また、bindValue()関数を使う際に、第一引数として1から始まる番号を振ります。今回はwhere句でuser_idしかカラムがないので、そのまま1を代入します。

$stmt -> bindValue(1, 1, PDO::PARAM_INT);   //値の紐付け

その他は名前付きplace holderと同じなので割愛します。
スクリーンショット 2021-06-10 7.43.23.png

参考サイト

https://www.php.net/manual/ja/class.pdo.php
https://www.php.net/manual/ja/pdo.prepare.php
https://www.php.net/manual/ja/pdostatement.bindvalue.php
https://www.php.net/manual/ja/pdostatement.bindparam.php
https://www.php.net/manual/ja/pdostatement.fetchall.php
https://www.php.net/manual/ja/pdostatement.execute.php
https://qiita.com/mpyw/items/b00b72c5c95aac573b71

0
0
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
0