Can anyone tell me how to insert records to database table via controller method?
2 Answers
Try this way
First way without model
$data = $this->getRequest()->getPost();
$entity_id =1;
$entity_type_id =4;
$attribute_id = 92;
$value = 'red';
$store_id =1;
$resource = Mage::getSingleton('core/resource');
$writeAdapter = $resource->getConnection('core_write');
$table = $resource->getTableName('some_table_name');
$query = "INSERT INTO {$table} (`entity_id`,`entity_type_id`,`attribute_id`,`value`,`store_id`) VALUES ($entity_id, $entity_type_id, $attribute_id, $value, $store_id);";
$writeAdapter->query($query);
Second way use model
$data = array(
'entity_id' => 1,
'entity_type_id' => 4,
'attribute_id' => 92,
'value' => 'Red',
'store_id' => 1
);
$model = Mage::getModel('your_model_name'); //for eg. Mage::getModel('catalog/product');
try {
$model->setData($data)
->save();
} catch (Exception $e) {
echo $e->getMessage();
}
You can check default core controllers file where it done in many places.
For example if you check file
app/code/core/Mage/Customer/controllers/AccountController.php
and action createPostAction()
you will get the idea how they are storing data for customer.
You can follow the same way for your custom table using your model
$model = Mage::getModel('modulename/modelname');
$model->setData($yourData);
$model->save();
You can set individual fields also
$model->setField($yourFieldValue);