Jordan Richards
Jordan Richards

Reputation: 35

How to sanitize query to accept table name as parameter PDO php

I have the following code which works, however, now i'm just wondering if this will be secure, and not sql injectable etc.

I cannot take the approach of whitelisting table names as for my web application, more tables will be generated randomly in the future and will be passed through a URL parameter of table, so therefore I will never know all of the tables.

I use the first query to determine if the table which is passed through the URL parameter actually exists, otherwise I will be exiting the script which i'm yet to add.

$db = "database1";
$table = $_GET['table'];
$stmt = $auth_table->runQuery("Select table_name, table_schema from information_schema.tables where table_schema = :db and table_name = :tablename");
$stmt->execute(array(":db"=>$db,":tablename"=>$table));
$tableRow=$stmt->fetch(PDO::FETCH_ASSOC);
$table_schema = $tableRow['table_schema'].".".$tableRow['table_name'];

$stmt = $auth_table->runQuery("Select * from ".$table_schema."");
$stmt->execute();
$testing=$stmt->fetch(PDO::FETCH_ASSOC);
print_r($testing['level']);
exit();

Upvotes: 2

Views: 546

Answers (1)

Jamie_D
Jamie_D

Reputation: 999

Whitelist your existing tables

$db = "database1";
$table = $_GET['table'];

$dbh = new PDO('mysql:host=localhost;dbname=database1', $user, $pass);
$tableSql = "SHOW TABLES FROM " . $db;       
$tableRes = $dbh->query($tableSQL); 
$tableArr  = $tableRes->fetch(PDO::FETCH_ASSOC);
$whitelist = $tableArr[0]['Tables_in_database1']; 
if(!in_array($table, $whitelist)){
    exit(); //Or RickRoll Them
}

Upvotes: 4

Related Questions