Php 如何正确地将数据保存到数据库?
我通常将新数据保存到数据库中,如下所示:Php 如何正确地将数据保存到数据库?,php,mysql,cakephp,cakephp-2.0,Php,Mysql,Cakephp,Cakephp 2.0,我通常将新数据保存到数据库中,如下所示: $this->MyTable->set(array( 'id' => $id, 'code' => $temp_code, 'status' => $status, 'age' => $age, 'location' => $location, 'money' => $money )); $this->MyTable->save(); $this->Adtweet->
$this->MyTable->set(array(
'id' => $id,
'code' => $temp_code,
'status' => $status,
'age' => $age,
'location' => $location,
'money' => $money
));
$this->MyTable->save();
$this->Adtweet->id = $id;
$this->Adtweet->saveField('code', $temp_code);
$this->Adtweet->saveField('status', $status);
如果数据库中已经存在ID,我将更新其相应字段,如下所示:
$this->MyTable->set(array(
'id' => $id,
'code' => $temp_code,
'status' => $status,
'age' => $age,
'location' => $location,
'money' => $money
));
$this->MyTable->save();
$this->Adtweet->id = $id;
$this->Adtweet->saveField('code', $temp_code);
$this->Adtweet->saveField('status', $status);
有没有更好或“适当”的方法来实现这一点
当我尝试输入一个已经存在的ID并使用set
函数时,我得到以下SQL完整性错误:
(错误:SQLSTATE[23000]:完整性约束冲突:密钥“PRIMARY”的1062重复条目“150245925”)
如何编写一个能够干净地处理重复条目而不返回错误的函数?如果要保存新数据,只需使用
Model::save()
:
如果要更新数据,只需使用相同的方法,而无需调用Model::create()
另见:
编辑:
我想这就是你想要的:
$this->ModelName->id = $id;
if (!$this->ModelName->exists()) {
$this->ModelName->create();
}
$this->ModelName->save($data);
发布数据示例
Array
(
[ModelName] => Array
(
[column1] => value
[column2] => value
[column3] => value
)
)
尝试添加此选项
if ($this->request->is('post')) {
$this->ModelName->create();
$this->ModelName->save($this->request->data);
}
请尝试编辑此文件
if ($this->request->is('post')) {
$this->ModelName->id = 2;
$this->ModelName->save($this->request->data);
}
谢谢你的回复。要使用“create”,我想我应该这样做:因为在检查模型之前,我甚至不知道数据库中是否存在ID<代码>$isIdExists=$this->ModelName->find('first',array('conditions'=>array('ModelName.id'=>$id)--
if($isIdExists){$this->ModelName->create();}
感谢您的更新。当我尝试$this->$ModelName->create()时;
,创建了一个ID为零的行。但是我有一个正确的用户ID。所以我像这样更改了它$this->ModelName->create(array('ID'=>$ID));
创建了正确的行。但是在那之后!$this->ModelName->exists()
仍然是真的..我想我应该越来越多地工作..也许你忘了将ID列设置为自动增量
?好吧,我对成员数据使用这个模型。所以ID列是用户的twitter ID。每个用户都有唯一的twitter ID,并且它不是从零开始的。所以我用ID参数创建了新记录,如果它不存在的话。主这里的问题是,cakephp希望主键名为“id”,如果不是这种情况,您需要告诉它您的模型。因此,如果主键字段名为“twitter\u user\u id”,您必须在模型中设置public$primaryKey='twitter\u user\u id'
。