B-219 Sec-55 Noida, India
+918010221733

Select,Insert,Update,and Delete data (CRUD) In Magento

In this blog post I am trying to describe the custom Magento query like the Select,Insert,Update,and Delete query in Magento

I have a database table named “testimonial” with the following fields given below:
id : int(11), auto increment, primary key
title : varchar(200)
content : text
status : 0 or 1
Suppose, the module name of my extension is “mytestimonial”. The code to select, insert, update, and delete data from the “testimonial” table.

SELECT DATA

$item->getData() //prints array of data from 'testimonial' table.
$item->getTitle() //prints the only the title field.

To print content, we need to write $item->getContent().

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


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 values to be inserted.

$data = array(‘title’=>’hello EWA’,’content’=>’This is for the Testing on the Insert data’,’status’=>1);
$model = Mage::getModel(‘mytestimonial/mytestimonial’)->setData($data);
try {
        $insertId = $model->save()->getId();
        echo “Data has been saved successfully. Insert ID: “.$insertId;
    } catch (Exception $e){
     echo $e->getMessage(); 
}

 

UPDATE DATA

$sid 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.

// $sid = $this->getRequest()->getParam(‘id’);
$sid = 5;
$data = array(‘title’=>’hello EWA’,’content’=>’This is for the Testing on the Update data’,’status’=>0);
$model = Mage::getModel(‘mytestimonial/mytestimonial’)->load($sid)->addData($data);
try {
        $model->setId($sid)->save();
        echo “Data has been updated successfully.”;
       
    } catch (Exception $e){
        echo $e->getMessage();
}

 


DELETE DATA

$sid is the database table row id to be deleted.

// $sid = $this->getRequest()->getParam('id');
$sid = 5;
$model = Mage::getModel('mytestimonial/mytestimonial');
try {
$model->setId($sid)->delete();
echo "Data deleted successfully.";

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

This is all about the custom query in magento and I think now you can perform select, insert, update and delete in your custom module in magento code.

(Visited 123 times, 1 visits today)

Leave a reply

You must be logged in to post a comment.