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



在使用CakePHP将数据保存到数据库中之前,我正在尝试使用mysql-real-escape-string来清理输入。我收到以下错误

mysql_real_escape_string() [function.mysql-real-escape-string]: Access 拒绝用户"nobody"@"localhost"(使用密码:NO)

我的代码:

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

从文档中:

如果你使用 CakePHP 的

ORM 方法(如 find() 和 save()))和正确的数组表示法(即 array('field' => $value))而不是原始 SQL,CakePHP 已经保护你免受 SQL 注入的侵害。

所以忘记手动调用mysql_real_escape_string().

我猜你还没有连接到 mysql db。尝试使用正确的凭据mysql_connect() 和 mysql_select_db()

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_* 函数更受支持

复杂查询的情况下 Sanitize::escape() 为 CakePHP 2.x 或 CakePHP 3.x 手动构造

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

最新更新