views:

782

answers:

2

I am talking about doing something like this:

LOCK TABLE page WRITE;

SELECT * FROM page WHERE col = 'value';

INSERT INTO page(col1, col2) VALUES('val1', val2);

UNLOCK TABLES;

A: 

I think you would need to use an adapter, I'm not sure locking works though.

$model->getAdapter()->query($sql, $bind);

piddl0r
+2  A: 

I don't see an actual Zend DB method to lock tables, but maybe just do this:

//Lock Table
$sql = "LOCK TABLE page WRITE";
$db->fetchRow($sql);

//Get your data
$sql = "SELECT * FROM page WHERE col='value'";
$result = $db->fetchAll($sql);

//Make the insert
$data = array( 'col1' => 'val1', 'col2' => 'val2' );
$db->insert('page', $data);

//Unlock tables
$sql = "UNLOCK TABLES";
$db->fetchRow($sql);

Probably not the best solution and it's untested. But it might work for ya.

UPDATE: I have come across a better solution for you. Use transactions:

// Start a transaction explicitly.
$db->beginTransaction();

try {
    //Get your data
    $sql = "SELECT * FROM page WHERE col='value'";
    $result = $db->fetchAll($sql);
    //Make the insert
    $data = array( 'col1' => 'val1', 'col2' => 'val2' );
    $db->insert('page', $data);

    // If all succeed, commit the transaction and all changes
    // are committed at once.
    $db->commit();

} catch (Exception $e) {
    // If any of the queries failed and threw an exception,
    // we want to roll back the whole transaction, reversing
    // changes made in the transaction, even those that succeeded.
    // Thus all changes are committed together, or none are.
    $db->rollBack();
    echo $e->getMessage();
}

I have recently come across the same problem and transactions have worked great. Definitely the way to go.

Jakobud
i guess i'll have to do it this way.. thanks for the response.
deepanshuyadav