LoginSignup
2
2

More than 5 years have passed since last update.

データベースクラスを作成するぞ - vol.3

Last updated at Posted at 2015-08-15

まえがき

とりあえず現段階では、あるメソッドから
メインとなるメソッドの呼び出しまで、なんとかOK。

その中で"発行したいsql文"を、
どーにかこーにか作成できた状態。
(いやー大問題を抱えているんですけどね…。)

作成中DBクラス

DBクラス
class DB {
    private $_instance;
    Private $_pdo;

    private function __construct() {
        $dsn="mysql:dbname=【データベース名】;host=【ホスト名】;charset=utf8";
        $user="【ユーザー名】";
        $pass="【パスワード】";
        try {
            $this->_pdo= new PDO($dsn, $user, $pass);
            echo 'coonected!';
        } catch(PDOException $e) {
            die($e->getMessage());
        }
    }

    public static function getInstance() {
        if(!isset(self::$_instance)) {
            self::$_instance = new DB();
        }
        return self::$_instance;
    }

    public function mainAction($action, $table, $where = null) {
        if(isset($where)) {
            $field = $where[0];
            $operator = $where[1];
            $value = $where[2];
            // *1
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} {$value}";
        } else {
            // *2
            $sql = "{$action} FROM {$table}";
        }
    }

    public function select($table, $where = null) {
        $this->mainAction('SELECT *', $table, $where);
    }

    public function delete($table, $where = null) {
        $this->mainAction('DELETE', $table, $where);
    }
}

// 呼び出し例
DB::getInstance()->select('【テーブル名】', array('【フィールド名】', '【演算子】', '【値】'));

"SELECT" と "DELETE" を、どこで入れようかなーと
ちょっと迷いましたが、後になるとmainAction()が
大きくなりそうだったので、早い目にいれておきました。

ここまでで、なんとなーく形にはなってきた…よね。きっと。

あとがき

ただし、(*1)(*2)のsql文が、大きな問題を抱えております。

このままの状態で、sql文を通してしまうと
噂の"SQLインジェクション"の恰好の的。な、はず。

その為に、プリペアドステートメントを
実行することになるのですが…。

んーやっぱり、別のfunctionを作成した方が良いのかな…。
あまり1箇所にまとめ過ぎるとダメだ、って聞いたような気もするし。

ということは…

あるメソッドを呼び出すと、(今後作成していくinsertやupdateも含めて)
いくつかのメソッドを通っていき、最終的に "A" or "B"
どちらかのメソッドで終了(実行)となりそう、かな。

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