3

Can anyone tell me how to insert records to database table via controller method?

2
  • Are you trying access Models via Controllers or something else ?
    – Prateek
    Commented Dec 19, 2015 at 10:34
  • Yes.. That only.. I want to insert record to database table.
    – vedu
    Commented Dec 19, 2015 at 10:46

2 Answers 2

8

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();
}
0
1

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);
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.