1

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;

4 Answers4

10

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.

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
2

Zend_Db transactions do not guarantee locks! See this on how to make proper isolated transactions.

Database transactions in Zend Framework: Are they isolated?

Community
  • 1
  • 1
jack
  • 21
  • 1
1

$this->_db->getConnection()->exec('LOCK TABLES page');

klausk
  • 11
  • 1
0

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

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

piddl0r
  • 2,431
  • 2
  • 23
  • 35