How to update data in a database
Consider the following code in a datamapper, to save data into a database:
/**
* Save data into the database
* @param Site_Model_User $model
* @throws InvalidArgumentException
*/
public function save($model) {
if (!$model instanceof Model_User) {
throw new InvalidArgumentException('Model is not of correct type');
}
$data = array();
$data['username'] = $model->getUserName();
$data['firstname'] = $model->开发者_开发知识库;getFirstName();
$data['lastname'] = $model->getLastName();
$data['email'] = $model->getEmail();
$data['password'] = $model->getPassword();
$data['role'] = $model->getRole();
$data['pic'] = $model->getImage();
if ($model->getId() < 0) {
// nieuw object, doe insert
$id = $this->getDao()->insert($data);
$model->setId($id);
} else {
// bestaand object, doe update
$where = $this->getDao()->getAdapter()->quoteInto('id = ?', $model->getId());
$this->getDao()->update($data, $where);
}
}
What i do is that i save my object everytime. When doing an insert this is no problem. Because I send a complete filled update. But lets say I want to update my password. And i do a update. It doesn't let me do the update because it says that certain values can not be 0.
For example: Mysqli statement execute error : Column 'username' cannot be null"
What is the best soultion for this? Should I first load the whole object again from the database, then change the fields and then do the update? Or are ther other better, more common solutions?
Thanks
yes, you have to load all the fields from the database and fill up all the required form fields except password fields and then change your password and submit the form. this will help you for validate required field not NULL and go further.
Thanks.
Chandres maheshwari's answers is a valid option, but consider this as an alternative.
I'm not familiar with the framework you are using, but can't you build your query yourself, or at least select the fields you want to update?
I would do something like:
public function save($model) {
if (!$model instanceof Model_User) {
throw new InvalidArgumentException('Model is not of correct type');
}
$data = array();
if($model->getUserName())
$data['username'] = $model->getUserName();
if($model->getFirstName())
$data['firstname'] = $model->getFirstName();
// .... and so on ...
if ($model->getId() < 0) {
// nieuw object, doe insert
$id = $this->getDao()->insert($data);
$model->setId($id);
} else {
// bestaand object, doe update
$where = $this->getDao()->getAdapter()->quoteInto('id = ?', $model->getId());
$this->getDao()->update($data, $where);
}
}
Of course you should check whether a field is false/NULL because it has not been modified or because the user actually wants it empty (i.e. deleted) or make sure that all the fiels are not NULL when you are inserting.
精彩评论