Sadee
Sadee

Reputation: 3180

In Cakephp, how to prevent sql injection if I use direct mysql queires rather than using models?

I have to deal with large mysql DB. Sql queries with lot of calculations (in select clause) and several kind of conditions in where clauses. So, I decided to use row/direct sql queries to deal with DB by using $db = ConnectionManager::getDataSource('default');

If I use this, how I prevent sql injection in mysql query? "mysql_real_escape_string" no longer exists. Is there any way to use PDO within CakePHP?

Upvotes: 0

Views: 642

Answers (2)

Sadee
Sadee

Reputation: 3180

You can use this in your controller (or component)

// Initiate PDO connection
$this->_pdocon = $this->WhateverYourModel->getDataSource()->getConnection();
try {

    // Select Query
    $company = "What";
    $stmt = $this->_pdocon->prepare('SELECT * FROM `agents` WHERE `company` LIKE :company LIMIT 2');
    $stmt->bindValue(':company', $company, PDO::PARAM_STR);

    // Start transaction
    $this->_pdocon->begin();

    // Loop through the events
    if( $stm->execute() ) {
        while ($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
            $stmt2 = $this->_pdocon->prepare("INSERT INTO `company` 
                        (`id`, `name`, `identityno`, `modified`, `created`) 
                        VALUES 
                        (NULL, :name, :identityno, NOW(), NOW())");
            $stmt2->bindValue(':name', $row['name'], PDO::PARAM_STR);
            $stmt2->bindValue(':identityno', $row['id'], PDO::PARAM_INT);
            $stmt2->execute();

        }
    }

    // Commit transaction
    $this->_pdocon->commit();

    // Get last insert Id
    $row_id = $this->_pdocon->lastInsertId();
    var_dump($row_id); 

} catch (PDOException $e) {

    // Rollback transaction
    $this->_pdocon->rollback();

    echo "! PDO Error : " . $e->getMessage() . "<br/>";
}

This is what I ended-up. Using PDO has been solved thousands of issues. Now the system is fast and no memory exhaust error. And I can not putting all issues, errors what I got, in my question. It's good to giving direct answer rather trying to changing questions in here!

Upvotes: 2

Anton
Anton

Reputation: 420

A large part of the point of cakePhp is not to do this. Therefore I would recommend not doing this.

Cakephp has a its own implementation for accessing a DB and you should use it if at all possible. Is there a particular reason you want to go around it?

if you realy want to, you can still use mysqli but I cant recommend it.

Upvotes: 1

Related Questions