Skip to content
Advertisement

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?

Advertisement

Answer

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;

    ...
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement