Insert ,Update ,Delete and Select Records from Database Tables in Magento

Sunday, September 23, 2012
You can select,insert,update and delete data in the Magento wby using their models concept.
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.

6 comments:

  1. Demian said...:

    Hi Rajesh, that's exactlly what i was looking for, thanks a lot buddy.

  1. rajthegr8 said...:

    Thanks demian....keep following the posts...

  1. Anonymous said...:

    The below 1 is not working for me... do u know y?

    $model = Mage::getModel('test/test');
    $collection = $model->getCollection();
    foreach($collection as $testData){
    print_r($testData->getData());
    print_r($testData->getFirstname());
    }

  1. Anonymous said...:

    M trying to access data through getCollection but it isn't accessible

  1. Anonymous said...:

    while useing delete option i got a fatal error "Fatal error: Call to a member function setId() on a non-object"
    will any budy tell how i overcome it

  1. Anonymous said...:

    what is test

Post a Comment