Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Wednesday, June 26, 2013

How to use Magento to take care SQL Injection in writing raw query to insert/update

Sometime you want to use Magento to write raw insert/update queries directly, and you also want to take care of SQL Injection but you are unable to find how Magento does this.
E.g. this is your initial query
1
2
3
4
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
$query = "INSERT INTO Contact(Name, Email, Company, Description, Status, Date)
    VALUES ('$name', '$email', '$company', '$desc', '0', NOW())";
$write->query($query);
Now you want to change the above query to prevent the possible SQL Injection. You don’t want to use the default “mysql_real_escape_string()” built-in function of PHP.
You can take care of SQL Injection in above query like following
01
02
03
04
05
06
07
08
09
10
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
$query = "INSERT INTO Contact(Name, Email, Company, Description, Status, Date)
     VALUES (:name, :email, :company, :desc, '0', NOW())";
$binds = array(
    'name'      => $name,
    'email'     => $email,
    'company'   => $company,
    'desc'      => $desc,
);
$write->query($query, $binds);

No comments:

Post a Comment