在使用CakePHP将数据保存到我的数据库之前,我尝试使用mysql-real-escape-string对输入进行sanatize。我收到以下错误
mysql_real_escape_string()[function.mysql-real-escape-string]:访问 拒绝用户' nobody' @' localhost' (使用密码:否)
我的代码:
public function admin_videos($id = null) {
if(!($this->isLogged() && $this->isAuthorized())) {
$this->redirect(array('controller' => 'users', 'action' => 'login', 'admin' => true));
}
if ($this->request->is('post')) {
$this->request->data['MovieVideo']['video'] = mysql_real_escape_string($this->request->data['MovieVideo']['video']);
$this->request->data['MovieTrailer']['video'] = mysql_real_escape_string($this->request->data['MovieTrailer']['video']);
if ($this->Movie->saveAll($this->request->data)) {
$this->Session->setFlash('The movie has been saved', 'admin/flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('The movie could not be saved. Please, try again.', 'admin/flash_error');
}
} else {
$this->request->data = $this->Movie->find('first', array('conditions' => array('Movie.id' => $id), 'contain' => array('MovieTrailer', 'MovieVideo')));
}
}
答案 0 :(得分:5)
来自docs:
如果使用CakePHP的ORM方法(例如find()和save())和正确的数组表示法(即数组('field'=> $ value))而不是原始SQL,CakePHP已经保护您免受SQL注入
所以忘记手动调用mysql_real_escape_string()
。
答案 1 :(得分:2)
我猜你还没有连接到mysql db。 尝试使用正确凭据的mysql_connect()和mysql_select_db()
答案 2 :(得分:1)
mysql_real_escape_string()需要连接到数据库作为第二个参数,除非您已经打开了连接: http://php.net/manual/en/function.mysql-real-escape-string.php
您可以尝试以下方法之一:
一般来说,我建议使用PDO,因为它更好的OO,并且比mysql_ *函数更受支持
答案 3 :(得分:1)
如果为CakePHP 2.x或CakePHP 3.x手动构建Sanitize::escape()
的复杂查询
$connection = ConnectionManager::get('default');
$clean_string = $connection->quote('dirty"string--%/\');