Web版レシート管理作成記 CRUDの「R」について(2/2)

プログラミング

UserデータのCRUDのR(Read)の2回シリーズの第2回です。
今回は、MVCの全体の構成と関連の概念図とプログラムコードを掲載します。

MVCの全体の構成と各構成間の関連の概念図です。

上記の構成を簡単に説明します。

1. UserTestEntry.php
ブラウザのURLで指定されたスクリプトファイルです。
UserTestControllerクラス(2.)のインスタンスを作成し、run()メソッドを呼び出します。
コード掲載はこちら

2. UserTestController.php
「UserデータのCRUD」ページ(3.UserTestMenuView.html)の表示と当ページから送出されたリクエストの処理を行うコントローラークラスです。
1.で呼び出されたrun()メソッドでは「UserデータのCRUD」ページ(3.UserTestMenuView.html)へリダイレクトします。
「UserデータのCRUD」ページから送出されたPOSTリクエストは、handleRequest()メソッドで処理します。
当メソッドにおいてPOSTリクエストが「照会」と判定された場合、「Userデータの検索」ページ(5.UserTestSCondView.html)へリダイレクトします。
コード掲載はこちら

3. UserTestMenuView.html
2.のrun()メソッド内で呼び出される「UserデータのCRUD」ページです。
当ページで「新規作成」「更新」「削除」「照会」のいずれかのボタンが選択されると、Fromタグの送信先に指定されたUserTestSCondController.php(6.)にリクエストが送信されます。
コード掲載はこちら

4. UserTestReceiveRequest.php
UserTestControllerクラス(2)のインスタンスを作成し、handleRequest()メソッドを呼び出します。
コード掲載はこちら

5. UserTestSCondView.html
「userデータの検索」ページです。
当ページで、すべてのUserデータを検索するか、名前での一致検索(完全一致、前方一致、後方一致、前方後方一致)をするか指定します。
Fromタグの送信先に指定されたUserTestSCondController.php(6.)にリクエストが送信されます。
コード掲載はこちら

6. UserTestSCondController.php
「userデータの検索」ページから送出されたリクエストの処理を行うコントローラークラスです。
具体的には、次の処理を行います。
「userデータの検索」ページで指定された検索方法でデータ検索します。
検索結果に基づいてページング情報を算出します。
(総データ数、最初に表示するデータのインデックスNo.、最後に表示するデータのインデックスNo.)
セッションからデータ操作(CRUD)を取り出して、データ操作に応じたデータ表示ページにリダイレクトします。
データ操作が”R”の場合、「Userテーブルのデータ」ページ(7. UserTestDataView.php)へリダイレクトします。
コード掲載はこちら

7. UserTestDataView.php
ページング情報に基づいてデータを表示します。
[前ページ][次ページ][戻る]ボタンが選択されたとき、Fromタグの送信先に指定されたUserTestReadDataController.php(8.)にリクエストが送信されます。
コード掲載はこちら

8. UserTestReadDataController.php
ページング情報に基づいて「Userテーブルのデータ」ページにデータを表示します。
[前ページ][次ページ][戻る]ボタンが選択されたときのPOSTリクエスト処理を行います。
[前ページ][次ページ]が選択された場合はそれぞれのページング情報を算出し、新たな「Userテーブルのデータ」ページを表示するために7.UserTestDataView.phpへリダイレクトします。
[戻る]が選択されたときは、「userデータの検索」(5.)ページへリダイレクトします。
コード掲載はこちら

9. SessionModel.php
セッションの開始やセッション変数のSet、Getなどを行うセッションに係るモデルクラスです。
コード掲載はこちら

10. PDOModel.php
データベースの接続やSQL文の発行を行うデータベースに係るモデルクラスです。
コード掲載はこちら

11. PagingModel.php
ページング情報を算出するモデルクラスです。
ページング情報は、総データ数、最初に表示するデータのインデックスNo.、最後に表示するデータのインデックスNo.です。
コード掲載はこちら

コードの掲載

UserTestEntry.php
<?php
/*************************************************
 * Enty point
 * ブラウザからhttp://****.****.xdomain.jp/UserTestEntry.php
 * で呼ばれる最初の起動プログラム
 * コントローラー(PagingTestController.PHP)のrunメソッドを呼び出します
 */


require_once( __DIR__ . '/UserTestController.php');
$controller = new UserTestController();
$controller->run();
exit;
?>

戻る

UserTestController.php
<?php
/**
 * Description of UserTestController
 * 「UserテーブルのCRUD」ページに対するコントローラーの役割
 * 
 */
class UserTestController{
    //クラス変数を定義します
    private $table_data = [];                              //userテーブルデータを保持する配列変数
    private $paging_info = [];                             //ページング情報を保持する配列変数
    private $session_model;                                //SessionModelのインスタンスを保持

    const CREATE = 'C';                                    // データ操作:Create
    const READ   = 'R';                                    // データ操作:Read
    const UPDATE = 'U';                                    // データ操作:Update
    const DELETE = 'D';                                    // データ操作:Delete

    //コンストラクター
    public function __construct() {
        require_once(__DIR__ . '/SessionModel.php');

        $this->session_model = new SessionModel();         //Modelクラスのインスタンスを生成
    }

    /******************************************************
     * 当メソッドはUserTestEntry.phpから呼ばれます
     * 「UserデータCRUD」ページを表示します
     *****************************************************/
    public function run() {
    
        //「UserデータCRUD」ページ(UserTestMenuView.html)へリダイレクト
        header('Location: UserTestMenuView.html');
        
        exit();
    }

    /******************************************************
     * 当メソッドはUserTestRecieveRequest.phpから呼ばれます
     * 「UserデータCRUD」ページにおいて
     * [新規作成]、[更新]、[削除]、[照会]、[終了]ボタンが
     * 選択された時のPOSTリクエストの処理を行います
     *****************************************************/
    public function handleRequest() {

        $this->session_model->sessionstart();                  // セッションを再開します


        if (isset($_POST['create']) && $_POST['create'] == "新規作成") {
            //「新規作成」ボタンが選択されたときの処理

            $this->session_model->set_data_operation(CREATE);  // データ操作 'C':Createをセッションに保管します

            header('Location: UserTestCreateView.html');       //「Userデータ新規作成」ページへリダイレクト

        } elseif (isset($_POST['update']) && $_POST['update'] == "更  新") {
            //「更  新」ボタンが選択されたときの処理

            $this->session_model->set_data_operation(UPDATE);  // データ操作 'U':Updateをセッションに保管

            header('Location: UserTestSCondView.html');        // 「Userデータの検索条件入力」ページへリダイレクト

        } elseif (isset($_POST['delete']) && $_POST['delete'] == "削  除") {
            //「削  除」ボタンが選択されたときの処理
            
            $this->session_model->set_data_operation(DELETE);  // データ操作 'D':Deleteをセッションに保管

            header('Location: UserTestSCondView.html');        // 「Userデータの検索条件入力」ページへリダイレクト

        
        } elseif (isset($_POST['read']) && $_POST['read']     == "照  会") {
            //「照  会」ボタンが選択されたときの処理

            $this->session_model->set_data_operation(READ);    // データ操作 'R':Readをセッションに保管

            header('Location: UserTestSCondView.html');        // 「Userデータの検索条件入力」ページへリダイレクト

        
        } elseif (isset($_POST['end']) && $_POST['end']       == "終  了") {
            //「終  了」ボタンが選択されたときの処理
            
            $_SESSION = [];                                    // セッション変数を空にします

            // クッキーを削除します
            if (ini_get("session.use_cookies")) {
                $params = session_get_cookie_params();
                setcookie(session_name(), '', time() - 42000,
                    $params["path"], $params["domain"],
                    $params["secure"], $params["httponly"]
                );
            }

            session_destroy();                                 // セッションを破壊します

            header('Location: UserTestEndView.html');          //終了ページへリダイレクト

        }
    }
}
?>

戻る

UserTestMenuView.html
<HTML>
<HEAD>
<!-- スタイルシートのパス -->
<LINK REL="stylesheet" TYPE="text/css" HREF="style_menu.css">

<TITLE>{$title}</TITLE>
</HEAD>
<meta charset="utf-8">
<BODY>

<DIV CLASS="main">

    <H1>UserテーブルのCRUD</H1>

    <form action="UserTestReceiveRequest.php" method="post">

        <table>
            <tr>
                <td></td>
                <td><input type="submit" name="create" value="新規作成"></td> 
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="update" value="更  新"></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="delete" value="削  除"></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="read" value="照  会"></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="end" value="終  了"></td>
                <td></td>
            </tr>
        </table>

    </form>

</DIV>

</BODY>
</HTML>

戻る

UserTestReceiveRequest.php
<?php
/*************************************************
 *  UserTestView.phpのPOSTリクエストを受取り、
 *  コントローラー(UserTestController.php)の
 *  handleRequest()メソッドを呼び出します
*/

require_once __DIR__ . '/UserTestController.php';

$controller = new UserTestController();
$controller->handleRequest();
exit;


?>

戻る

UserTestSCondController.php
<?php
/**
 * Description of UserTestSCondController
 * 「Userデータの検索条件入力」ページのリクエストUserテーブルの検索画面に対するコントローラーの役割
 * 
 */
class UserTestSCondController{
    //クラス変数を定義します
    private $table_data = [];                              //userテーブルデータを保持する配列変数
    private $paging_info = [];                             //ページング情報を保持する配列変数
    private $session_model;                                //SessionModelのインスタンスを保持
    private $pdo_model;                                    //PDOMdelのインスタンスを保持
    private $paging_model;                                 //PagingModelインスタンスを保持
    private $data_operation;                               //データ操作(C,R,U,D)を保持

    const CREATE = 'C';                                    // データ操作:Create
    const READ   = 'R';                                    // データ操作:Read
    const UPDATE = 'U';                                    // データ操作:Update
    const DELETE = 'D';                                    // データ操作:Delete

    //コンストラクター
    public function __construct() {
        require_once(__DIR__ . '/SessionModel.php');
        require_once(__DIR__ . '/PDOModel.php');
        require_once(__DIR__ . '/PagingModel.php');
        
        //Modelクラスのインスタンスを生成します
        $this->session_model = new SessionModel();
        $this->pdo_model = new PDOModel();
        $this->paging_model = new PagingModel();
    }

    /******************************************************
     * 当メソッドは「Userデータの検索条件入力」ページ
     * UserSCondView.htmlから呼ばれます
     * [検索開始]、[戻る]、「前ページ]、[次ページ]ボタンが
     * 選択された時のPOSTリクエストの処理を行います
     * [検索開始]ボタンが選択されたとき、
     * 指定された検索条件でUserデータを抽出し、
     * データ操作(U,D,R)ごとのデータ表示ページへリダイレクト
     * します。
     *****************************************************/
    public function handleRequest() {

        $this->session_model->sessionstart();                                    //セッションを開始    

        if (isset($_POST['search']) && $_POST['search'] == "検索開始") {
            //「検索開始」ボタンが選択されたときの処理

            $this->pdo_model->db_connect();                                      //データベースに接続

            $this->data_operation = $this->session_model->get_data_operation();  //セッションからデータ操作(R,U.D)を取り出し

            $searchOption = isset($_POST['searchop']) ? $_POST['searchop'] : ''; // ラジオボタンの選択値(すべて検索 or 条件検索)を取得

            if ($searchOption == 'all') {
                // [すべて検索]が選択されたときの処理
                $this->table_data = $this->pdo_model->select_all();          //Userテーブルデータを全件取得し、その返り値を配列に代入

            } elseif ($searchOption == 'condition') {
                // [条件検索]が選択されたときの処理
                $searchname = isset($_POST['searchname']) ? $_POST['searchname'] : '';  //名前を取得
                $matching = isset($_POST['match']) ? $_POST['match'] : '';              //マッチング方法を取得
                                                                                        //(完全一致、前方一致、後方一致、前方後方一致)
                //Userテーブルデータをマッチング検索で取得し、その返り値を配列に代入
                $this->table_data = $this->pdo_model->select_matching($searchname,$matching); 
            }

            if($this->data_operation == UPDATE || $this->data_operation == DELETE){
                //table_dataに要素flgを追加する処理
            }
                        
            $this->session_model->set_user_table($this->table_data);             //Userテーブルデータをセッションに保管
        
            $this->paging_info = $this->paging_model->init($this->table_data);   //初回に表示するページングの値を算出
        
            $this->session_model->set_paging_info($this->paging_info);           //初回に表示するページングデータをセッションに保管


            // データ操作(R,U,D)ごとのページを表示する処理
            if($this->data_operation == UPDATE){
                // データ操作がUPDATEの場合
                //header('Location: UserTestUpdateView.html');
            
            }else if($this->data_operation == DELETE){
                // データ操作がDELETEEの場合
                //header('Location: UserTestDeleteView.html');

            }else if($this->data_operation == READ){
                // データ操作がREADの場合参照
                header('Location: UserTestDataView.php');                        //「userテーブルのデータ」ページへリダイレクト
            }

        } elseif (isset($_POST['back']) && $_POST['back'] == "戻 る") {
            //「戻 る」ボタンが選択されたときの処理
            
            unset($_SESSION['ses_data_operation']);                              // セッション変数(ses_data_operation)を削除

            header('Location: UserTestMenuView.html');                           //「UserテーブルのCRUD」ページへリダイレクト

        }
    }
}

// コントローラーのインスタンスを作成し、handleRequestメソッドを呼び出す
/********************************************************
* クラスの外に記述されたコードは、PHPスクリプトが実行された際に
* コントローラーのインスタンスを作成し、
* リクエストの処理を行うためのメソッドを呼び出すためのものです。
* これにより、フォームのPOSTリクエストが適切に処理され、
* ユーザーが行ったアクションに応じて必要な処理が実行されます。
*********************************************************/
$controller = new UserTestSCondController();
$controller->handleRequest();
?>

戻る

UserTestSCondView.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style_Create.css">
    <title>userデータの検索</title>
</head>
<body>
<div class="main">
    <h1>userデータの検索</h1>
    <form id="form" name="form" method="post" action="UserTestSCondController.php">
        
        <table>
            <!-- すべて検索:文字マッチングの指定ができない 条件検索:名前と文字マッチングで検索-->
            <tr>
                <td><input type="radio" name="searchop" value="all" checked onclick="toggleInputs()">すべて検索</td>
            </tr>
            <tr>
                <td><input type="radio" name="searchop" value="condition" onclick="toggleInputs()">条件検索</td>
            </tr>
        </table>
        <br><br>
        <span id="ConditionMessage" style="display: none;"></span>
        <!--<label>文字列マッチング条件を指定してください。</label>-->
        <table class="maxwidth">
            <tr><td colspan="3"><p></p></td></tr>
            <tr><td colspan="3"><p></p></td></tr>
            <tr>
                <td class="label">名   前</td>
                <td>
                    <input type="text" name="searchname" size="40" id="searchname">
                    <span id="NameErrorMessage" class="error" style="display: none;"></span>
                </td>
            </tr>
        </table>
        <p></p>
        <br>
        <table>
            <tr>
                <td><input type="radio" name="match" value="ExactMatch" id="exactMatch">完全一致</td>
            </tr>
            <tr>
                <td><input type="radio" name="match" value="PrefixMatch" id="prefixMatch">前方一致</td>
            </tr>
            <tr>
                <td><input type="radio" name="match" value="SuffixMatch" id="suffixMatch">後方一致</td>
            </tr>
            <tr>
                <td><input type="radio" name="match" value="SubstringMatch" id="substringMatch">前方後方一致</td>
            </tr>
        </table>
        <br>
        <table id="button_erea">
            <tr>
                <td style="text-align: center"><input type="submit" name="search" value="検索開始"></td>
                <td style="text-align: center"><input type="submit" name="back" value="戻 る"></td>
            </tr>
        </table>

    </form>
</div>

<script type="text/javascript">
function toggleInputs() {
    // エレメント:input[name="searchop"][value="all"]のcheckプロパティ値(true or false)を
    // isAllSelectedに代入します
    var isAllSelected = document.querySelector('input[name="searchop"][value="all"]').checked;

    // isAllSelectedの値(true oe false)をdisabledプロパティにセットします
    document.getElementById('searchname').disabled = isAllSelected;
    document.getElementById('exactMatch').disabled = isAllSelected;
    document.getElementById('prefixMatch').disabled = isAllSelected;
    document.getElementById('suffixMatch').disabled = isAllSelected;
    document.getElementById('substringMatch').disabled = isAllSelected;
    
    // エラーメッセージ表示領域を取得
    var message = document.getElementById("ConditionMessage");

    // エラーメッセージをリセット
    message.style.display = "none";

    if (!isAllSelected) {
        message.innerText = "文字列マッチング条件を指定してください。";
        message.style.display = "inline";
    }
    
}

document.addEventListener('DOMContentLoaded', function() {
    toggleInputs(); // 初期状態を設定
});
</script>
</body>
</html>

戻る

UserTestSCondController.php
<?php
/**
 * Description of UserTestSCondController
 * 「Userデータの検索条件入力」ページのリクエストUserテーブルの検索画面に対するコントローラーの役割
 * 
 */
class UserTestSCondController{
    //クラス変数を定義します
    private $table_data = [];                              //userテーブルデータを保持する配列変数
    private $paging_info = [];                             //ページング情報を保持する配列変数
    private $session_model;                                //SessionModelのインスタンスを保持
    private $pdo_model;                                    //PDOMdelのインスタンスを保持
    private $paging_model;                                 //PagingModelインスタンスを保持
    private $data_operation;                               //データ操作(C,R,U,D)を保持

    const CREATE = 'C';                                    // データ操作:Create
    const READ   = 'R';                                    // データ操作:Read
    const UPDATE = 'U';                                    // データ操作:Update
    const DELETE = 'D';                                    // データ操作:Delete

    //コンストラクター
    public function __construct() {
        require_once(__DIR__ . '/SessionModel.php');
        require_once(__DIR__ . '/PDOModel.php');
        require_once(__DIR__ . '/PagingModel.php');
        
        //Modelクラスのインスタンスを生成します
        $this->session_model = new SessionModel();
        $this->pdo_model = new PDOModel();
        $this->paging_model = new PagingModel();
    }

    /******************************************************
     * 当メソッドは「Userデータの検索条件入力」ページ
     * UserSCondView.htmlから呼ばれます
     * [検索開始]、[戻る]、「前ページ]、[次ページ]ボタンが
     * 選択された時のPOSTリクエストの処理を行います
     * [検索開始]ボタンが選択されたとき、
     * 指定された検索条件でUserデータを抽出し、
     * データ操作(U,D,R)ごとのデータ表示ページへリダイレクト
     * します。
     *****************************************************/
    public function handleRequest() {

        $this->session_model->sessionstart();                                    //セッションを開始    

        if (isset($_POST['search']) && $_POST['search'] == "検索開始") {
            //「検索開始」ボタンが選択されたときの処理

            $this->pdo_model->db_connect();                                      //データベースに接続

            $this->data_operation = $this->session_model->get_data_operation();  //セッションからデータ操作(R,U.D)を取り出し

            $searchOption = isset($_POST['searchop']) ? $_POST['searchop'] : ''; // ラジオボタンの選択値(すべて検索 or 条件検索)を取得

            if ($searchOption == 'all') {
                // [すべて検索]が選択されたときの処理
                $this->table_data = $this->pdo_model->select_all();          //Userテーブルデータを全件取得し、その返り値を配列に代入

            } elseif ($searchOption == 'condition') {
                // [条件検索]が選択されたときの処理
                $searchname = isset($_POST['searchname']) ? $_POST['searchname'] : '';  //名前を取得
                $matching = isset($_POST['match']) ? $_POST['match'] : '';              //マッチング方法を取得
                                                                                        //(完全一致、前方一致、後方一致、前方後方一致)
                //Userテーブルデータをマッチング検索で取得し、その返り値を配列に代入
                $this->table_data = $this->pdo_model->select_matching($searchname,$matching); 
            }

            if($this->data_operation == UPDATE || $this->data_operation == DELETE){
                //table_dataに要素flgを追加する処理
            }
                        
            $this->session_model->set_user_table($this->table_data);             //Userテーブルデータをセッションに保管
        
            $this->paging_info = $this->paging_model->init($this->table_data);   //初回に表示するページングの値を算出
        
            $this->session_model->set_paging_info($this->paging_info);           //初回に表示するページングデータをセッションに保管


            // データ操作(R,U,D)ごとのページを表示する処理
            if($this->data_operation == UPDATE){
                // データ操作がUPDATEの場合
                //header('Location: UserTestUpdateView.html');
            
            }else if($this->data_operation == DELETE){
                // データ操作がDELETEEの場合
                //header('Location: UserTestDeleteView.html');

            }else if($this->data_operation == READ){
                // データ操作がREADの場合参照
                header('Location: UserTestDataView.php');                        //「userテーブルのデータ」ページへリダイレクト
            }

        } elseif (isset($_POST['back']) && $_POST['back'] == "戻 る") {
            //「戻 る」ボタンが選択されたときの処理
            
            unset($_SESSION['ses_data_operation']);                              // セッション変数(ses_data_operation)を削除

            header('Location: UserTestMenuView.html');                           //「UserテーブルのCRUD」ページへリダイレクト

        }
    }
}

// コントローラーのインスタンスを作成し、handleRequestメソッドを呼び出す
/********************************************************
* クラスの外に記述されたコードは、PHPスクリプトが実行された際に
* コントローラーのインスタンスを作成し、
* リクエストの処理を行うためのメソッドを呼び出すためのものです。
* これにより、フォームのPOSTリクエストが適切に処理され、
* ユーザーが行ったアクションに応じて必要な処理が実行されます。
*********************************************************/
$controller = new UserTestSCondController();
$controller->handleRequest();
?>

戻る

UserTestDataView.php
<?php
    
    session_name('PHPSESSION_MEMBER');                     // セッション名セット
    session_start();                                       // セッション開始
    
    // セッションからUserテーブルデータとページング情報を取り出します
    $table_data  = isset($_SESSION['ses_table_data']) ? $_SESSION['ses_table_data'] : [];
    $paging_info = isset($_SESSION['ses_paging_info']) ? $_SESSION['ses_paging_info'] : [];
    
?>
<!-- Userテーブルのデータをブラウザに表示するテストプログラムです -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">

<style>
    div.main{
            width: 960px;
            min-height:300px;
            margin:0 0 0 0;
            padding:10px;
            background-color:#ffffff;
    }
    table{border: 0; border-collapse: collapse;}
    #button_area{width:100%}
    h1{text-align: center; color: #002060;  background-color:#F4B084; line-height: 120%}
    .label2{border: solid 1px #000000; border-collapse: collapse; height: 30px;}
    .label3{color: #ffffff; background-color:#305496; font-weight: 600; border: solid 1px #000000; border-collapse: collapse; text-align: center; height: 25px;}
    .func_button{color:#ffffff; background-color:#4472c4; font-weight: 600; width: 80px; height: 40px;font-size:11pt;}
    #back{
        float : left;
        text-align: left;
    }
    #next{
        text-align : right;
    }
    .select_button{
        line-height:20pt;
        padding:2px 10px 2px 10px;
        border-style: solid;
        border-width: 1px;
        border-color: 000000;
        text-decoration:none;
        font-size:11pt;
        font-weight: 600;
        text-align: center;
        color:#800080;
        border-color: 000000;
        background-color:#d9d9d9;
    }
</style>

<title>user table data</title>
</head>

<body>

<div class="main">

<h1>userテーブルのデータ</h1>

<form action="UserTestReadDataController.php" method="post">

<table style="width:100%;">

    <tr>
        <th style="width:115px; text-align: center" class="label3">AI</th>
        <th style="width:220px; text-align: center" class="label3">User ID</th>
        <th style="width:220px; text-align: center" class="label3">パスワード</th>
        <th style="width:405px; text-align: center" class="label3">名前</th>
    </tr>
    <?php

		if($paging_info['total_record'] != 0){
			for($i = $paging_info['first_record']; $i <= $paging_info['last_record']; $i++){
    ?>
                <tr>
                    <td class="label2" style="text-align: center;">
                        <?= htmlspecialchars($table_data[$i]['AI_User']) ?>
                    </td>
                    <td class="label2" style="text-align: left;">
                        <?= htmlspecialchars($table_data[$i]['UID']) ?>
                    </td>
                    <td class="label2" style="text-align: left;">
                        <?= htmlspecialchars($table_data[$i]['password']) ?>
                    </td>
                    <td class="label2" style="text-align: left">
                        <?= htmlspecialchars($table_data[$i]['name']) ?>
                    </td>
                </tr>
    <?php
            }
        } else {
            echo "<tr><td colspan='4' class='label2' style='text-align: center;'>表示するデータがありません。</td></tr>";
        }
    ?>

</table>

<div id="back">
	<?php
		if($paging_info['first_record'] != 0){
	?>
			<input type="submit" name="back" value="≪前ページ">
	<?php
		}
	?>
</div>

<div id="next">
	<?php

		if ($paging_info['last_record'] > 0 && $paging_info['last_record'] < floor(($paging_info['total_record'] - 1) / $paging_info['lines']) * $paging_info['lines']) {
	?>
			<input type="submit" name="next" value="次ページ≫">
	<?php
		}
	?>
</div>

<p></p>
<table id="button_area" style="width:100%">
    <tr>
        <td style="width:33%; text-align: center;"></td>
        <td style="text-align: center;"><input class="func_button" name="return" value="戻る" type="submit" /></td>
        <td style="width:33%; text-align: center;"></td>
    </tr>
</table>
<table>

</table>

</form>
<p>paging info</p>
<p><?php echo "total:" . $paging_info['total_record']; ?></p>
<p><?php echo "first:" . $paging_info['first_record']; ?></p>
<p><?php echo "last:" . $paging_info['last_record']; ?></p>


</div>

</body>
</html>

戻る

UserTestReadDataController.php
<?php
/**
 * Description of UserTestReadDataController
 * 「userテーブルのデータ」ページに対するコントローラー
 * 
 */
class UserTestReadDataController{
    //クラス変数を定義します
    private $paging_info = [];                             //ページング情報を保持する配列変数
    private $session_model;                                //SessionModelのインスタンスを保持
    private $paging_model;                                 //PagingModelインスタンスを保持

    //コンストラクター
    public function __construct() {
        require_once(__DIR__ . '/SessionModel.php');
        require_once(__DIR__ . '/PagingModel.php');
        
        //Modelクラスのインスタンスを生成します
        $this->session_model = new SessionModel();
        $this->paging_model = new PagingModel();
    }

    /******************************************************
     * 当メソッドは「userテーブルのデータ」ページ
     * UserSTestDataView.htmlから呼ばれます
     * [戻る]、「前ページ]、[次ページ]ボタンが
     * 選択された時のPOSTリクエストの処理を行います
     *****************************************************/
    public function handleRequest() {

        $this->session_model->sessionstart();                                    //セッションを開始    

        if (isset($_POST['back']) && $_POST['back'] == "≪前ページ") {
            //「前ページ」ボタンが選択されたときの処理

            $this->paging_info = $this->session_model->get_paging_info();        //現在のページング情報を得る

            $this->paging_info = $this->paging_model->back($this->paging_info);  //前ページのページング情報を算出

            $this->session_model->set_paging_info($this->paging_info);           //前ページングのページング情報をセッションに保管

            header('Location: UserTestDataView.php');                            //「userテーブルのデータ」ページへリダイレクト

        } elseif (isset($_POST['next']) && $_POST['next'] == "次ページ≫") {
            //「次ページ」ボタンが選択されたときの処理
            
            $this->paging_info = $this->session_model->get_paging_info();        //現在のページング情報を得る

            $this->paging_info = $this->paging_model->next($this->paging_info);  //次ページのページング情報を算出

            $this->session_model->set_paging_info($this->paging_info);           //次ページングのページング情報をセッションに保管
            
            header('Location: UserTestDataView.php');                            //「userテーブルのデータ」ページへリダイレクト

        } elseif (isset($_POST['return']) && $_POST['return'] == "戻る") {
            //「戻る」ボタンが選択されたときの処理

            header('Location: UserTestSCondView.html');                          //「userデータの検索」ページへリダイレクト
        }
    }
}

// コントローラーのインスタンスを作成し、handleRequestメソッドを呼び出す
/********************************************************
* クラスの外に記述されたコードは、PHPスクリプトが実行された際に
* コントローラーのインスタンスを作成し、
* リクエストの処理を行うためのメソッドを呼び出すためのものです。
* これにより、フォームのPOSTリクエストが適切に処理され、
* ユーザーが行ったアクションに応じて必要な処理が実行されます。
*********************************************************/
$controller = new UserTestReadDataController();
$controller->handleRequest();
?>

戻る

SessionModel.php
<?php
/**
 * Description of SessionModel
 * セッションに係る次の処理を受け持つクラスです
 *
 * セッションの開始処理とセッションへのデータ保管や取出し
 * を行います
 *
 */
class SessionModel {

    //クラス変数を定義します
    protected $sessname = 'PHPSESSION_MEMBER';             //セッション名を「PHPSESSION_MEMBER」にします
    protected $table_data = [];                            //userテーブルデータを保持する配列変数
    protected $paging_info  = [];                          //ページング情報を保持する配列変数
    protected $data_operation = '';                        //データ操作('C':Create,'R':Read,'U':Update,'D':Delete)を保持する変数

    //*****************************************************
    // コンストラクター
    //*****************************************************
    public function __construct() {
    }

    //*****************************************************
    // セッションの開始処理をします
    //*****************************************************
    public function sessionstart() {

        if (session_status() != PHP_SESSION_ACTIVE) {
        
            // セッションが非アクティブならセッションを開始します
            if ($this->sessname != "") {
                //セッション名を確実に「PHPSESSION_MEMBE」するためのコードです
                session_name($this->sessname);
            }
            session_start();  // セッション開始
        }
        
        return;
    }

    //*****************************************************
    // userテーブルデータをセッションに保管します
    //*****************************************************
    public function set_user_table(array $table_data) {
        
        $this->table_data = $table_data;
        
        // セッション変数(ses_table_data)を削除します
        unset($_SESSION['ses_table_data']);
        
        // userテーブルデータをセッション変数(ses_table_data)に保管します
        $_SESSION['ses_table_data'] = $this->table_data;
        
        return;
    }
    
    //*****************************************************
    // Userテーブルデータをセッションから取り出します
    //*****************************************************
    public function get_user_table() {   
    
        // セッションからuserテーブルデータを取り出します
        $this->table_data = isset($_SESSION['ses_table_data']) ? $_SESSION['ses_table_data'] : [];
    
        // 取り出したuserテーブルデータを返します
        return $this->table_data;
    }
 
    //*****************************************************
    // ページング情報をセッションに保管します
    //*****************************************************
    public function set_paging_info(array $paging_info) {
    
        $this->paging_info = $paging_info;
        
        // セッション変数(ses_paging_info)を削除します        
        unset($_SESSION['ses_paging_info']);
        
        // ページング情報をセッション変数(ses_paging_info)に保管します
        $_SESSION['ses_paging_info'] = $this->paging_info;
        
        return;
    }
    
    //*****************************************************
    // ページング情報をセッションから取り出します
    //*****************************************************
    public function get_paging_info() {   
    
        // セッションからページング情報を取り出します
        $this->paging_info = isset($_SESSION['ses_paging_info']) ? $_SESSION['ses_paging_info'] : [];
    
        // 取り出したページング情報を返します
        return $this->paging_info;
    }
 
     //*****************************************************
    // データ操作(C,R,U,Dのどれか)をセッションに保管します
    //*****************************************************
    public function set_data_operation($data_operation) {
        
        $this->data_operation = $data_operation;
        
        // セッション変数(ses_data_operation)を削除します
        unset($_SESSION['ses_data_operation']);
        
        // データ操作(C,R,U,Dのどれか)をセッション変数(ses_data_operation)に保管します
        $_SESSION['ses_data_operation'] = $this->data_operation;
        
        return;
    }
    
    //*****************************************************
    // Userテーブルデータをセッションから取り出します
    //*****************************************************
    public function get_data_operation() {   
    
        // セッションからデータ操作(C,R,U,Dのどれか)を取り出します
        $this->data_operation = isset($_SESSION['ses_data_operation']) ? $_SESSION['ses_data_operation'] : '';
    
        // 取り出したデータ操作(C,R,U,Dのどれか)を返します
        return $this->data_operation;
    }
    
}
?>

戻る

PDOModel.php
<?php
/**
 * Description of PDOModel
 * データベースに係る処理を受け持つクラスです
 */
class PDOModel {

    //クラス変数を定義します
    protected $pdo;                                        //PDOライブラリアプリのインスタンスを保持
    protected $host;                                       //ホスト情報
    protected $dbname;                                     //データベース名
    protected $dbusr;                                      //データベース接続ユーザー名
    protected $dbpass;                                     //データベース接続パスワード
    
    protected $table_data = [];                            //userテーブルデータを保持する配列


    //*****************************************************
    // コンストラクター
    //*****************************************************
    public function __construct() {
    
        // データベース接続情報を変数にセットします
        $this->host = '****.***.xdomain.ne.jp';
        $this->dbname = '****_receipt';
        $this->dbusr = '********_kr';
        $this->dbpass = '********';
    }

    //*****************************************************
    // DB接続処理
    //*****************************************************
    public function db_connect() {
        // DB接続処理
        try {
            $this->pdo = new PDO("mysql:host={$this->host};dbname={$this->dbname};charset=utf8", $this->dbusr, $this->dbpass);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        } catch(PDOException $Exception) {
            die('DB Connect Error: ' . $Exception->getMessage());
        }
        
        return;
    }

    //*****************************************************
    // userテーブルへselect文発行
    // 下記select文はuserテーブルからAI_Userの値が0~200のデータを取り出します
    //*****************************************************
    public function select_usertable() {
    
        // select文を生成して実行します
        try {
            $sql= "SELECT * FROM user WHERE AI_User BETWEEN :AIFrom AND :AITo";
            $stmh = $this->pdo->prepare($sql);
            $stmh->bindValue(':AIFrom', 0, PDO::PARAM_INT);
            $stmh->bindValue(':AITo', 200, PDO::PARAM_INT);
            
            $stmh->execute();                              //select文を実行します

            // select文で抽出したデータを1行ずつ取出して$table_data[]にセットします
            while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
                $this->table_data[] = $row;
            }
        } catch (PDOException $Exception) {
            die('DB select Error: ' . $Exception->getMessage());
        }
        
        // テーブルデータの配列($table_data[])を返します
        return $this->table_data;
    }
    
    //*****************************************************
    // 全件検索
    //*****************************************************
    public function select_all() {
    
        // select文を生成して実行します
        try {
            $sql= "SELECT * FROM user";
            $stmh = $this->pdo->prepare($sql);
            
            $stmh->execute();                              //select文を実行します

            // select文で抽出したデータを1行ずつ取出して$table_data[]にセットします
            while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
                $this->table_data[] = $row;
            }
        } catch (PDOException $Exception) {
            die('DB select Error: ' . $Exception->getMessage());
        }
        
        // テーブルデータの配列($table_data[])を返します
        return $this->table_data;
    }   
    
    //*****************************************************
    // 一致検索
    //*****************************************************
    public function select_matching($name, $matching) {

        // パターンマッチングの設定
        switch ($matching) {
            case 'ExactMatch':                             // 完全一致
                $pattern = $name;
                break;
            case 'PrefixMatch':                            // 前方一致
                $pattern = "%" . $name;
                break;
            case 'SuffixMatch':                            // 後方一致
                $pattern = $name . "%";
                break;
            case 'SubstringMatch':                         // 前方後方一致
                $pattern = "%" . $name . "%";
                break;
            default:
                $pattern = $name;
        }

        // select文を生成して実行します
        try {
            if ($matching == 'ExactMatch') {
                $sql = "SELECT * FROM user WHERE name = :name";
            } else {
                $sql = "SELECT * FROM user WHERE name LIKE :name";
            }
            $stmh = $this->pdo->prepare($sql);

            // バインドパラメータを設定
            $stmh->bindValue(':name', $pattern, PDO::PARAM_STR);

            // SQL文を実行
            $stmh->execute();

            // select文で抽出したデータを1行ずつ取出して$table_data[]にセット
            while ($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
                $this->table_data[] = $row;
            }
        } catch (PDOException $Exception) {
            die('DB select Error: ' . $Exception->getMessage());
        }

        // テーブルデータの配列($table_data[])を返します
        return $this->table_data;
    }

    //*****************************************************
    // Userデータインサート処理
    //*****************************************************
    public function insert_user($insert_user_data){
        try {
            $this->pdo->beginTransaction(); // トランザクション開始

            $sql = "INSERT INTO user
                    (UID, password, name)
                    VALUES
                    (:UID, :password, :name)";

            $stmh = $this->pdo->prepare($sql); // SQL文を解析し、準備ステートメントオブジェクト(PDOStatement)を生成

            // インサートする値を紐づけ
            $stmh->bindValue(':UID', $insert_user_data['UID'], PDO::PARAM_STR);
            $stmh->bindValue(':password', $insert_user_data['password'], PDO::PARAM_STR);
            $stmh->bindValue(':name', $insert_user_data['name'], PDO::PARAM_STR);

            $stmh->execute(); // insert文を実行
            $this->pdo->commit(); // コミット
            return true;
        } catch (PDOException $Exception) {
            $this->pdo->rollBack();
            print "エラー:" . $Exception->getMessage();
            return false;
        }
    }

}

?>

戻る

PagingModel.php
<?php
/**
 * Description of PagingModel
 * ページングに係る処理を受け持つクラスです
 */
class PagingModel {

    //クラス変数を定義します
    private $table_data = [];                              //userテーブルデータを保持する配列変数
    private $paging_info = [];                             //ページング情報を保持する配列変数
    
    //  <<<< ページング情報<$paging_info[]>について >>>>
    //
    //  ページング情報とは、1ページに表示するデータを特定するための情報です
    //  $paging_info[](連想配列)に次の情報を保持します
    //
    //  キー名        : 値
    //  total_record  : userテーブルのデータ数を保持します
    //  first_record  : ページに表示する先頭の$table_data[]のインデックス番号(0からカウントします)
    //  last_record   : ページに表示する最後の$table_data[]のインデックス番号(0からカウントします)
    //  lines         : 1ページに表示する最大行数でLINES_PER_PAGEの値を保持します
    
    
    const LINES_PER_PAGE = 10;                             // 1ページ表示する最大の行数 定数で定義します
    
    //*****************************************************
    // コンストラクター
    //*****************************************************
    public function __construct() {
    }

    //*****************************************************
    // 最初に表示するデータのページング情報を求めます
    //*****************************************************
    public function init(array $table_data) {
    
        // ページング情報を初期化します
        $this->paging_info = array(
            "total_record"  => 0,
            "first_record"  => 0,
            "last_record"   => 0,
            "lines" => self::LINES_PER_PAGE                // 定数を参照
        );
        
        $this->table_data = $table_data;                   // 引数で受け取ったuserテーブルデータをセットします
        
        $this->paging_info['total_record'] = count($this->table_data);   // userテーブルデータをカウントしトータルレコード数をセットします
        $this->paging_info['first_record'] = 0;            // 表示する先頭行に$table_data[]のインデックス0をセットします。
        
        // first_record,last_recordを求めます
        if ($this->paging_info['total_record'] == 0) {
             $this->paging_info['last_record'] = 0;
        } elseif ($this->paging_info['total_record'] <= self::LINES_PER_PAGE) {
            // ページ表示件数より総レコード数が小さい場合
            $this->paging_info['last_record'] = $this->paging_info['total_record'] - 1;
        } else {
            // ページ表示件数より総レコード数が大きい場合
            $this->paging_info['last_record'] = self::LINES_PER_PAGE - 1;
        }
        
        return $this->paging_info;                         // ページング情報を返します
    }

    //*****************************************************
    // [前ページ]がクリックされた時に表示するデータの
    // ページング情報を求めます
    //*****************************************************
    public function back(array $paging_info) {
    
        $this->paging_info = $paging_info;
        
        // first_record,last_recordを求めます
        if ($this->paging_info['first_record'] != 0) {
            $this->paging_info['last_record'] = $this->paging_info['first_record'] - 1;
            $this->paging_info['first_record'] -= self::LINES_PER_PAGE;
        }
        
        return $this->paging_info;                         // ページング情報を返します
    }
    
    //*****************************************************
    // [次ページ]がクリックされた時に表示するデータの
    // ページング情報を求めます
    //*****************************************************
    public function next(array $paging_info) {
    
        $this->paging_info = $paging_info;
        
        // first_record,last_recordを求めます
        if ($this->paging_info['last_record'] < $this->paging_info['total_record'] - 1) {
            $this->paging_info['first_record'] += self::LINES_PER_PAGE;
            if ($this->paging_info['last_record'] + self::LINES_PER_PAGE < $this->paging_info['total_record']) {
                $this->paging_info['last_record'] += self::LINES_PER_PAGE;
            } else {
                $this->paging_info['last_record'] = $this->paging_info['total_record'] - 1;
            }
        }
        
        return $this->paging_info;                         // ページング情報を返します
    }
}
?>

戻る

上記コードに掲載していませんが、Web版レシート管理作成記 CRUDの「C」について(2/2)で紹介した「新規作成」機能のプログラムも動作します。
ここまでで、CRUDのC(Create)とR(Read)が完成しました。
次回はU(Update)について掲載します。

タイトルとURLをコピーしました