Magento – Alternative Method for Executing Update Queries Using PHP

databasequery

I have a script that runs outside of Magento to do some "maintenance" work on the database. Here is an example of how it works:

<?php

require_once('../app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

// Now you can run ANY Magento code you want

/**
     * Get the resource model
     */
    $resource = Mage::getSingleton('core/resource');

    /**
     * Retrieve the read connection
     */
    $readConnection = $resource->getConnection('core_read');

    $query = 'select * from salesrule_coupon where times_used="20";';

/**
     * Execute the query and store the results in $results
     */
     $results = $readConnection->fetchAll($query);

Works perfectly until I swap that SELECT query with an UPDATE query. Apparently, this is the reason: https://stackoverflow.com/questions/12979510/pdo-error-sqlstatehy000-general-error-when-updating-database

I attempted to swap the fetchAll($query) method with something like this:

mysql_query('update salesrule_coupon SET times_used="0" where code like "X%";');

But it seems that mysql_query function requires you to use the standard MySQL connection method. Seems like the solution is would be to swap out fetchAll() as I am already connected and able to use SELECT queries. Does anyone know what I need to modify in order to allow UPDATE queries to be performed?

Best Answer

Use

$writeConnection = $resource->getConnection('core_write');
$writeConnection->query("Update....");