2

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

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

4 回答 4

5

文档

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

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

于 2012-05-24T07:01:04.307 回答
2

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

于 2012-05-24T07:01:16.400 回答
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_* 函数更受支持

于 2012-05-24T07:42:11.357 回答
1

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

    $connection = ConnectionManager::get('default');
    $clean_string = $connection->quote('dirty"string--%/\');
于 2015-11-25T16:34:42.950 回答