Jensy Santana
Jensy Santana

Reputation: 13

Is it safe to use the name of a table as a parameter of a php function?

The function searches the $variable named table using SQL as showed here:

class Search{

    `public function query(){`

      `SELECT * FROM $tableName`

    `}`

}
$object = new Search();
$object->query('tableName');

Is this a good practice or a door to SQL Inyection?

Upvotes: 0

Views: 273

Answers (2)

i-man
i-man

Reputation: 568

The short answer is NO, don't do this.

That said it may be perfectly safe depending on where your parameter is coming from.

consider mapping a variable to the table names, so you can verify that you are only building a query with a valid table name and not open-ended text.

A simple solution could look something like this:

public function query($tableName){
    $allowedTables = ['accounts', 'items', 'products'];

    $table = in_array($tableName, $allowedTables) ? $tableName : null;

    if(empty($table)){
        return false;
    }

    $sql = "Select * FROM " . $table;

    ...
}

Upvotes: 1

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8059

You can do it in the safe way by "whitelisting" allowed tables. There are many different implementations depends on your needs. For example, get full or filtered list of your tables with:

SHOW TABLES; 

BTW, PHP has a function for this. Then check if input table is in the list.

I think it's safe way to do this.

Upvotes: 0

Related Questions