我使用codeigniter作为我的PHP框架,当我提交我的from到post到我的数据库时,我一直得到这个错误。
You must use the "set" method to update an entry
我不太确定这是什么意思,从我看过的其他帖子来看,每个人都说datamapper需要有一个值分配给对象。
由于我对这一切都是新手,有人能给我一个更好的解释吗?
这里是我的代码,它说我有错误:
class Add_book extends CI_Model {
public function add_book($data){
$this->db->insert('ST_ITM', $data);
}
}
?>
谢谢。
你需要做一些像这样的事情
class Add_book extends CI_Model {
public function add_book(){
// 'book_name' would be the name of your column in database table
$data = array(
'book_title' => $this->input->post('book_title'),
'book_author' => $this->input->post('book_author'),
'book_name' => $this->input->post('book_name')
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix . 'ST_ITM');
}
}
在视图中,输入将类似于示例
<input type="text" name="book_name" value="" />
<input type="text" name="book_title" value="" />
<input type="text" name="book_author" value="" />
最好在model中使用数据数组。然后在表单验证库的成功部分加载模型函数
对于所有到达这里的人,您不必在插入查询中使用set:
https://www.codeigniter.com/userguide3/database/query_builder.html插入数据
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
错误是由于插入数据构造错误(必须是一个数组)或未能编写正确的Active Record查询,例如未在插入数组之前添加表名。
但是,当我们使用set?
在更新或替换时需要绕过自动转义,例如:
$this->db->set('last_login', 'NOW()', FALSE);
$this->db->update(DB_PREFIX .'user', array('login_attempts' => 0));
第三个参数禁用自动转义。这为我们编写活动记录查询提供了必要的灵活性。
我得到这个错误时,我传递错误的变量到插入语句。
例如:
function($a){
$this->db->insert($aa); <-- error !!
}
所以我通过传递正确的变量来解决它,也就是$a
还要确保插入数组的格式正确为$a = array('columnname'=>'value');
例如,我想插入数据,所以我必须做下面的代码-
我的视图文件(Login_form.php)
<label>Username:</label> <input type="text" name="username" value="">
<label>Password:</label> <input type="password" name="password" value="">
我的模型文件(Model_login.php)
class Model_login extends CI_Model {
public function insert_entry()
{
$data= array(
'username'=>$this->input->post('username'), // here username and password are database fields.
'password'=>$this->input->post('password'),
);
$this->db->insert('login', $data); //here login is my database table's name
}
}
控制器文件(下)
class Login extends CI_Controller {
public function index()
{
$this->load->view('Login_form'); //to load view file
}
public function getLoginValues()
{
$this->load->model('Model_login'); //to load Model file
$data=$this->Model_login->insert_entry();//to load method of Model file
}
}
运行正常,检查一下
。
public function SetFoo($bar) {
$data = [
'YourColumnName' => 'Yes'
];
// Using Query Builder
$this->set($data);
$this->where('id',$bar);
$this->update();
}
如果您没有在模型的顶部添加以下
,则会抛出上述错误protected $allowedFields = ['YourColumnName'];
列可以存在于模型中,但不能使用set update访问,除非它位于allowedfields部分(它类似于代码查看列的私有/公共)
问题出在你的模型上。所以你必须检查数组$data
是否为空
像这样:
class Add_book extends CI_Model {
public function add_book($data){
if ( $data != null)
$this->db->insert('ST_ITM', $data);
}
}
?>