PHP – Using ARRAY_MAP to generate an ON DUPLICATE KEY UPDATE statement

This bit of code is very cool;

function getUpdateString($arrayKey, $arrayValue)
{
 return($arrayKey . ‘=’ . $arrayValue);
}
   $values['key1'] = ‘value1′;
   $values['key2'] = ‘value2′;
   $sql = ‘INSERT INTO table ( ‘ . implode(‘, ‘,array_keys($values)) . ‘ )
      VALUES ( ‘ . implode(‘, ‘,array_values($values)) . ‘ )
      ON DUPLICATE KEY UPDATE ‘ . implode(‘, ‘,array_map(‘getUpdateString’,array_keys($values),array_values($values)));

Returns a SQL statement:

INSERT INTO table ( key1, key2 ) VALUES ( value1, value2 ) ON DUPLICATE KEY UPDATE key1=value1, key2=value2;

Useful stuff.

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)