Search This Blog

Sunday, March 6, 2011

Magento: How to select, insert, update, and delete data


CRUD (Create Read Update Delete)

Database table named ‘article‘

INSERT DATA

$data contains 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('title'=>'test1,'content'=>'test2.','status'=>0);
$model = Mage::getModel('myarticle/myarticle')->setData($data);
try {
        $insertId = $model->save()->getId();
        echo "Data successfully inserted. Insert ID: ".$insertId;
    } catch (Exception $e){
     echo $e->getMessage();
}

SELECT DATA

$item->getData() prints array of data from ‘article’ table.
$item->getTitle() prints the only the title field.
Similarly, to print content, we need to write $item->getContent().
$model = Mage::getModel('myarticle/myarticle');
$collection = $model->getCollection();
foreach($collection as $item){
    print_r($item->getData());
    print_r($item->getTitle());
}

UPDAT

$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 = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'erewr','content'=>'dsfsdf','status'=>1);
$model = Mage::getModel('myarticle/myarticle')->load($id)->addData($data);
try {
        $model->setId($id)->save();
        echo "Data updated successfully.";

    } catch (Exception $e){
        echo $e->getMessage();
}

DELET

$id is the database table row id to be deleted.
// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('myarticle/myarticle');
try {
        $model->setId($id)->delete();
        echo "Data deleted successfully.";

    } catch (Exception $e){
        echo $e->getMessage();
}

1 comment:

  1. I dont know which fool says that this is his copy righted material...
    This is a 100% open source blog for magento lovers.
    -
    Author

    ReplyDelete