For example,a table named ‘testdata‘ with the following fields:-
id : int, auto increment, primary key
firstname: varchar
lastname: varchar
Lets take a module named 'test'. Below is the code to select, insert, update, and delete data from the ‘testdata‘ table.
TO INSERT DATA
$data have array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
$data = array('firstname'=>'rajesh','lastname'=>'nautiyal');
$model = Mage::getModel(test/test)->setData($data);
$model->save();
TO SELECT DATA
$testData = Mage::getModel(test/test)->load(2);
$testData->getData();
It will prints array of data for id=2 from ‘testData’ table.
$testData->getFirstname() prints the only the firstname field.
Similarly, to print lastname, $testData->getLastname().
$model = Mage::getModel('test/test');
$collection = $model->getCollection();
foreach($collection as $testData){
print_r($testData->getData());
print_r($testData->getFirstname());
}
TO UPDATE DATA
$id is the database table row id to be updated.
$data contains array of data to be updated. The key of the array should be the database table’s field name and the value should be the value to be updated.
$id = 11;
$data = array('firstname'=>'Raj','lastname'=>'naughty');
$model = Mage::getModel('test/test')->load($id)->addData($data);
$model->setId($id)->save();
TO DELETE DATA
$id is the database table row id to be deleted.
// $id = $this->getRequest()->getParam('id');
$id = 13;
$model = Mage::getModel('test/test');
$model->setId($id)->delete();
Like this way we can select, insert, update and delete data in tables in our new module and in any magento code.
Share this on Facebook
Tweet this
Hi Rajesh, that's exactlly what i was looking for, thanks a lot buddy.