假设,我有一个名为mynews
. 以下是表格中的select, insert, update, and delete data
代码news
。
INSERT DATA
$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
$item->getData() prints array of data from ‘news’ table.
$item->getTitle() prints the only the title field.
同样,要打印内容,我们需要编写$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
是要更新的数据库表行 ID。
$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
是要删除的数据库表行id。
// $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();
}
通过这种方式,您可以在自定义模块和任何magento code
.
来源: http: //blog.chapagain.com.np/magento-how-to-select-insert-update-and-delete-data/