LoginSignup
0
0

PDO (PHP Data Objects)・2回目

Last updated at Posted at 2024-04-27

はじめに

PDOについてまとめる・2回目

SQLを発行しデータを登録する

insert.phpで入力された内容を、insert_process.phpで登録処理する。

insert_form.php
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>データの登録</title>
</head>

<body>
    <form action="insert.php" method="POST">
        <div>
            <label for="isbn">ISBNコード</label>
            <input id="isbn" name="isbn" type="text" siza="25" maxlength="20">
        </div>
        <div>
            <label for="title">書名</label>
            <input id="title" name="title" type="text" siza="35" maxlength="150">
        </div>
        <div>
            <label for="price">価格</label>
            <input id="price" name="price" type="text" siza="5" maxlength="5">
        </div>
        <div>
            <label for="publish">出版社</label>
            <input id="publish" name="publish" type="text" siza="15" maxlength="30">
        </div>
        <div>
            <label for="published">刊行日</label>
            <input id="published" name="published" type="text" siza="15" maxlength="10">
        </div>
        <div>
            <input type="submit" value="登録">
        </div>
    </form>
</body>

</html>

DBに発行する一連の命令を管理するのは、PDOStatementオブジェクトの役割。
prepareメソッドでSQL命令を準備しexecuteメソッドで命令が送信/実行される。

insert_process.php
<?php
require_once __DIR__ . '../DbManager.php';

try {
    $db = getDb();
    $stt = $db->prepare('INSERT INTO book(isbn, title, price, publish, published) 
    VALUES(:isbn, :title, :price, :publish, :published)');
    $stt->bindValue(':isbn', '$_POST[isbn]');
    $stt->bindValue(':title', '$_POST[title]');
    $stt->bindValue(':price', '$_POST[price]');
    $stt->bindValue(':publish', '$_POST[publish]');
    $stt->bindValue(':published', '$_POST[published]');
    $stt->execute();
    header('Location: http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/insert_form.php');
} catch (PDOException $e) {
    die("エラーメッセージ:{$e->getMessage()}");
}

接続スクリプトの外部化

DbManager.php
<?php
function getDb(): PDO
{
    $dsn = 'mysql:dbname=selfphp; host=127.0.0.1; charset=utf8';
    $usr = 'selusr';
    $passwd = 'selfpass';

    $db = new PDO($dsn, $usr, $passwd);
    return $db;
}

PDOStatementオブジェクト

PDOStatementオブジェクトは、PDOオブジェクト$dbからprepareメソッドを呼び出すことで取得できる。
insert_process.phpにおける prepareメソッドに含まれる「:名前」という記述はプレイスホルダーを表す。
プレイスホルダーとはパラメータの置き場所のこと。
PDOオブジェクトではプレイスホルダーに対して実行時に任意のパラメータを引き渡すことができる。
(bindValueメソッドで実際にプレイスホルダーに値を設定している。)

prepareメソッド
PDO::prepare(string $statement[, array $driver_options]): PDOStatement

$statement : 発行するSQL命令
$driver_options : 動作オプション
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