tags:

views:

818

answers:

2

Why can't I pass the table name to a prepared PDO statement?

$stmt = $dbh->prepare('SELECT * FROM :table WHERE 1');
if ($stmt->execute(array(':table' => 'users'))) {
    var_dump($stmt->fetchAll());
}

Is there another safe way to insert a table name into a SQL query? With safe I mean that I don't want to do

$sql = "SELECT * FROM $table WHERE 1"
+1  A: 

Using the former isn't inherently more safe than the latter, you need to sanitize the input whether it's part of a parameter array or a simple variable. So I don't see anything wrong with using the latter form with $table, provided you make sure that the content of $table is safe (alphanum plus underscores?) before using it.

Adam Bellaire
Considering that the first option won't work, you have to use some form of dynamic query building.
Noah Goodrich
Yes, the question mentioned it won't work. I was trying to describe why it wasn't terribly important to even try to do it that way.
Adam Bellaire
+3  A: 

Please see the following: http://us3.php.net/manual/en/book.pdo.php#69304

Table and Column names cannot be replaced by parameters in PDO. In that case you will simply want to filter and sanitize the data manually. One way to do this is to pass in shorthand parameters to the function that will execute the query dynamically and then use a switch() statement to create a white list of valid values to be used for the table name or column name. That way no user input ever goes directly into the query. So for example:

function buildQuery( $get_var ) 
{
    switch($get_var)
    {
        case 1:
            $tbl = 'users';
            break;
    }

    $sql = "SELECT * FROM $tbl";
}

By leaving no default case or using a default case that returns an error message you ensure that only values that you want used get used.

Noah Goodrich