danielrsmith
danielrsmith

Reputation: 4060

Is there a way to do an "INSERT...ON DUPLICATE KEY UPDATE" in Zend Framework 1.5?

I would like to use ON DUPLICATE KEY UPDATE in Zend Framework 1.5, is this possible?

Example

INSERT INTO sometable (...)
VALUES (...)
ON DUPLICATE KEY UPDATE ...

Upvotes: 49

Views: 26564

Answers (7)

Vinod Sai
Vinod Sai

Reputation: 2122

Update to Pawel's Answer to support separate insert and update data, and also supports Zend Db Expressions

  class Model_Db_Abstract extends Zend_Db_Table_Abstract
    {
        protected $_name;
        protected $_primaryKey;

        public function insertOrUpdate($arrayData)
        {
            $insertDataValuesForQuery = [];
            $queryParams = [];
            foreach ($insertData as $key => $value) {
                if (gettype($value) == "object") {
                    array_push($insertDataValuesForQuery, $value->__toString());
                    continue;
                }
                array_push($insertDataValuesForQuery, "?");
                array_push($queryParams, $value);
            }

            $updateDataValuesForQuery = [];
            foreach ($updateData as $key => $value) {
                if (gettype($value) == "object") {
                    array_push($updateDataValuesForQuery, $key . " = " . $value->__toString());
                    continue;
                }
                array_push($updateDataValuesForQuery, $key . " = ?");
                array_push($queryParams, $value);
            }

            $query = 'INSERT INTO ' . $this->_name . ' (' . implode(',', array_keys($insertData)) . ') VALUES (' . implode(',', $insertDataValuesForQuery) . ') ON DUPLICATE KEY UPDATE ' . implode(' , ', $updateDataValuesForQuery);
            return $this->getAdapter()->query($query, $queryParams);
     }
}

Upvotes: 0

Pawel
Pawel

Reputation: 380

$arrayData = array('column1' => value1, 'column2' => value2, ...)

class Model_Db_Abstract extends Zend_Db_Table_Abstract
{
    protected $_name;
    protected $_primaryKey;

    public function insertOrUpdate($arrayData)
    {
        $query = 'INSERT INTO `'. $this->_name.'` ('.implode(',',array_keys($arrayData)).') VALUES ('.implode(',',array_fill(1, count($arrayData), '?')).') ON DUPLICATE KEY UPDATE '.implode(' = ?,',array_keys($arrayData)).' = ?';
        return $this->getAdapter()->query($query,array_merge(array_values($arrayData),array_values($arrayData)));
    }

}

USAGE:

eg. Model_Db_Contractors.php

class Model_Db_Contractors extends Model_Db_Abstract 
{

    protected $_name = 'contractors';
    protected $_primaryKey = 'contractor_id';

    ...
}

IndexController.php

class IndexController extends Zend_Controller_Action
{
 public function saveAction()
 {
  $contractorModel = new Model_Db_Contractors();
  $aPost = $this->getRequest()->getPost();

  /* some filtering, checking, etc */

  $contractorModel->insertOrUpdate($aPost);
 }
}

Upvotes: 4

Bill Karwin
Bill Karwin

Reputation: 562398

I worked for Zend and specifically worked on Zend_Db quite a bit.

No, there is no API support for the ON DUPLICATE KEY UPDATE syntax. For this case, you must simply use query() and form the complete SQL statement yourself.

I do not recommend interpolating values into the SQL as harvejs shows. Use query parameters.

Edit: You can avoid repeating the parameters by using VALUES() expressions.

$sql = "INSERT INTO sometable (id, col2, col3) VALUES (:id, :col2, :col3)
  ON DUPLICATE KEY UPDATE col2 = VALUES(col2), col3 = VALUES(col3)";

$values = array("id"=>1, "col2"=>327, "col3"=>"active");

Upvotes: 55

Rajdeep Rath
Rajdeep Rath

Reputation: 35

Use this instead:

REPLACE INTO sometable SET field ='value'.....

This will update if exists or just insert if not. This is a part of the standard mysql api.

Upvotes: 1

user212218
user212218

Reputation:

As a sidebar, you can simplify the ON DUPLICATE KEY UPDATE clause and reduce the amount of processing your script needs to do by using VALUES():

$sql = 'INSERT INTO ... ON DUPLICATE KEY UPDATE id = VALUES(id), col2 = VALUES(col2), col3 = VALUES(col3)';

See http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html for more information.

Upvotes: 6

Peter
Peter

Reputation: 13

you can simply do something like this:

set unique index on your id

and then

try {
   do insert here
} catch (Exception $e) {
   do update here
}

Upvotes: -8

Sergei Morozov
Sergei Morozov

Reputation: 622

@Bill Karwin: great solutions! But it would be greater if to use named placeholders (":id", ":col1", …) instead of questions signs. Than you wouldn’n need to duplicate values by array_marge. Also if to use "SET" syntax of "INSERT" instead of "VALUES", the code gets simplier to be generated automatically for any set of fields.

$sql = 'INSERT INTO sometable SET id = :id, col2 = :col2, col3 = :col3
    ON DUPLICATE KEY UPDATE id = :id, col2 = :col2, col3 = :col3';

Upvotes: 5

Related Questions