LoginSignup
0

More than 5 years have passed since last update.

プリペアドステートメントでテーブル名が指定できない時の対処

Posted at

PHPでプリペアドステートメントを使ってSQL文に値をバインドしていると思いますが、プリペアドステートメントはカラムの値にしか適応できないようです。

例えば、以下のようにPDOで接続して、SQL文にテーブル名をバインドしようとしてもうまくいきません。

// データベースへの接続開始
$dbh = new PDO($dsn, $user, $password);

// bindParamを利用して値をセット
$sql = 'CREATE TABLE :table_name (id text primary key, pass text not null);';
$sth = $dbh->prepare($sql);
$sth->bindParam(':table_name', $_POST['table_name']);
$sth->execute();

セキュリティ的に問題があるかもしれませんが、強引にテーブル名をセットする方法はあります。

// データベースへの接続開始
$dbh = new PDO($dsn, $user, $password);

// bindParamを利用して値をセット
$sql = 'CREATE TABLE ' .$_POST['table_name']. ' (id text primary key, pass text not null);';
$sth = $dbh->prepare($sql);
$sth->execute();

POSTしたデータを使ってテーブル名を指定する場合は、入力値チェックを行うなどして、くれぐれもSQLインジェクションに注意する必要があるでしょう。

参考:

プリペアドステートメントでテーブル名指定できないのか
http://absg.hatenablog.com/entry/2014/10/23/164254

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