Harsha M V
Harsha M V

Reputation: 54949

mysql-real-escape-string: Access denied in CakePHP

I am trying to sanatize the input using mysql-real-escape-string before i save the data into my database using CakePHP. And i get the following error

mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'nobody'@'localhost' (using password: NO)

My Code:

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

Upvotes: 2

Views: 2165

Answers (4)

Yaroslav
Yaroslav

Reputation: 2438

In case of complex queries manually constructed Sanitize::escape() for CakePHP 2.x or for CakePHP 3.x

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

Upvotes: 2

hobnob
hobnob

Reputation: 558

mysql_real_escape_string() requires a connection to a database as the second parameter unless you've already opened a connection: http://php.net/manual/en/function.mysql-real-escape-string.php

You can try one the following:

  • Try using mysql_escape_string (which is now deprecated)
  • Switch to PDO and use the quote function ( https://www.php.net/manual/en/pdo.quote.php )
  • Initialise a connection to your database first, and pass that connection to mysql_real_escape_string

Generally I would recommend using PDO as it's better OO, and is more supported than the mysql_* functions

Upvotes: 1

Erik-RW
Erik-RW

Reputation: 173

I guess you haven't connected to the mysql db. Try mysql_connect() and mysql_select_db() with the correct credentials

Upvotes: 2

Maerlyn
Maerlyn

Reputation: 34107

From the docs:

CakePHP already protects you against SQL Injection if you use CakePHP's ORM methods (such as find() and save()) and proper array notation (ie. array('field' => $value)) instead of raw SQL.

So forget about manually calling mysql_real_escape_string().

Upvotes: 5

Related Questions