Sam J.
Sam J.

Reputation: 353

Is it Safe to Send a Table Name in as Parameter

I am new to PDO and am creating a class. I want to make the code as clean as possible and have a few pages as possible. I am planning on sending the column and table names in as a parameter:

   function get($column, $table, $where) {
        global $db;
        $query = 'SELECT '.$column.' FROM '.$table.' WHERE '.$where.'';
        try {
            $statement = $db->prepare($query);
            $statement->execute();
            $result = $statement->fetchAll();
            $statement->closeCursor();
            return $result;
        } catch (PDOException $e) {
            $error_message = $e->getMessage();
            display_db_error($error_message);
        }
   } 

It works fine, but I am wondering how safe it would be considered.

Upvotes: 0

Views: 176

Answers (1)

Halfstop
Halfstop

Reputation: 1772

Your code is unsafe. Unless you're testing $column, $table and $where some place else in your code, this is ripe for sql injection. I wouldn't do what you plan on doing. It's a path to crazy bugs and errors. Allowing the user to control what table is accessed is obviously a major flaw in your application design.

Upvotes: 3

Related Questions