9

I like to prefix my tables in case I need to install the application to a host with only one database. I was wondering if there is a simple way of working with table prefixes using the PDO class?

At the moment, I am having to overwrite each method in my own database wrapped, replace %p with the prefix, and call the super method. It's works, but it isn't pretty!

j0k
  • 22,600
  • 28
  • 79
  • 90
Hanpan
  • 10,013
  • 25
  • 77
  • 115

1 Answers1

9

Extending the PDO class is probably the best option.

class MyPDO extends PDO
{
    protected $_table_prefix;
    protected $_table_suffix;

    public function __construct($dsn, $user = null, $password = null, $driver_options = array(), $prefix = null, $suffix = null)
    {
        $this->_table_prefix = $prefix;
        $this->_table_suffix = $suffix;
        parent::__construct($dsn, $user, $password, $driver_options);
    }

    public function exec($statement)
    {
        $statement = $this->_tablePrefixSuffix($statement);
        return parent::exec($statement);
    }

    public function prepare($statement, $driver_options = array())
    {
        $statement = $this->_tablePrefixSuffix($statement);
        return parent::prepare($statement, $driver_options);
    }

    public function query($statement)
    {
        $statement = $this->_tablePrefixSuffix($statement);
        $args      = func_get_args();

        if (count($args) > 1) {
            return call_user_func_array(array($this, 'parent::query'), $args);
        } else {
            return parent::query($statement);
        }
    }

    protected function _tablePrefixSuffix($statement)
    {
        return sprintf($statement, $this->_table_prefix, $this->_table_suffix);
    }
}
Pepijn Olivier
  • 927
  • 1
  • 18
  • 32
Glass Robot
  • 2,438
  • 19
  • 11
  • hi is it just me or on the function/method `_tablePrefixSuffix` the last bit `$this_table_suffix` is it suppose to be `$this->_table_suffix`? – Val Jun 18 '12 at 13:18
  • Not sure how this was possibly considered as working example, since `sprintf` expects format-string with special anchors, but the `$statement` argument is just a plain string, which simply gets ignored and returned as is. – Aleksandr Makov Sep 20 '12 at 08:01
  • Ok, figured it out. You just specify table name with anchors: `$table = "%1\$s{$table}%2\$s"` – Aleksandr Makov Sep 20 '12 at 08:26