Skip to content

Instantly share code, notes, and snippets.

@mathewjosephh
Last active November 3, 2016 08:14
Show Gist options
  • Save mathewjosephh/7aeef8aa6147d793cdaece271093893b to your computer and use it in GitHub Desktop.
Save mathewjosephh/7aeef8aa6147d793cdaece271093893b to your computer and use it in GitHub Desktop.
Magento : select, insert, update, and delete data
//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();
}
//$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.
//SELECT DATA
//$item->getData() prints array of data from ‘news’ table.
//$item->getTitle() prints the only the title field.
//Similarly, to print content, we need to write $item->getContent().
$model = Mage::getModel('mynews/mynews');
$collection = $model->getCollection();
foreach($collection as $item){
print_r($item->getData());
print_r($item->getTitle());
}
//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 = $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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment