Home / Magento / Magento 1x: How to select, insert, update, and delete data from custom table

Magento 1x: How to select, insert, update, and delete data from custom table

If you have a custom table which has model Mage::getModel(‘mynews/mynews’); then you can easily insert , select , update & delete data from your table see bellow codes.

INSERT DATA

$data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
$model = Mage::getModel('mynews/mynews')->setData($data);
try {
        $insertId = $model->save()->getId();
        echo "Data successfully inserted. Insert ID: ".$insertId;
    } catch (Exception $e){
     echo $e->getMessage();   
}

SELECT DATA

$model = Mage::getModel('mynews/mynews');
$collection = $model->getCollection();
foreach($collection as $item){
    print_r($item->getData());
    print_r($item->getTitle());
}

UPDATE DATA

// $id = $this->getRequest()->getParam('id');
$id = 2;
$data = array('title'=>'hello test','content'=>'test how are you?','status'=>0);
$model = Mage::getModel('mynews/mynews')->load($id)->addData($data);
try {
        $model->setId($id)->save();
        echo "Data updated successfully.";
       
    } catch (Exception $e){
        echo $e->getMessage(); 
}

DELETE DATA

// $id = $this->getRequest()->getParam('id');
$id = 3;
$model = Mage::getModel('mynews/mynews');
try {
        $model->setId($id)->delete();
        echo "Data deleted successfully.";
       
    } catch (Exception $e){
        echo $e->getMessage(); 
}

Hits: 122

%d bloggers like this: