mysql-real-escape-string:CakePHP中的访问被拒绝

时间:2012-05-24 06:56:46

标签: cakephp cakephp-2.1

在使用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')));
        }
    }

4 个答案:

答案 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

您可以尝试以下方法之一:

  • 尝试使用mysql_escape_string(现已弃用)
  • 切换到PDO并使用引用功能(http://uk3.php.net/manual/en/pdo.quote.php
  • 首先初始化与数据库的连接,并将该连接传递给mysql_real_escape_string

一般来说,我建议使用PDO,因为它更好的OO,并且比mysql_ *函数更受支持

答案 3 :(得分:1)

如果为CakePHP 2.x或CakePHP 3.x手动构建Sanitize::escape()的复杂查询

    $connection = ConnectionManager::get('default');
    $clean_string = $connection->quote('dirty"string--%/\');