Magento – Create/Change Custom Table Dynamically

databasemagento-1.9module

I'm wondering if there is any possibility of creating Custom Table outside install or update script, and without using the query("CREATE TABLE statement"), in Magento 1.9+

Best Answer

The Magento way of creating tables in install scripts is not using raw SQL but the Zend API:

$table = $installer->getConnection()
    ->newTable($installer->getTable('my/custom_table'))
    ->addColumn('id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
        'identity'  => true,
        'unsigned'  => true,
        'nullable'  => false,
        'primary'   => true,
        ), 'ID')
    ->addColumn(...);
$installer->getConnection()->createTable($table);

More on the topic: http://inchoo.net/magento/magento-install-install-upgrade-data-and-data-upgrade-scripts/


You can do the same anywhere else if you replace $installer->getConnection() with Mage::getSingleton('core/resource')->getConnection('core_write');.