Ivan
Ivan

Reputation: 433

Insert/Update Array data if new or exist

I have a form which displays existing data that can be edited and also allows for adding new data. How can I update and, if data is new, insert?

On submit I'm sending data like this:

 Array
(
  ['0'] => Array
    (
        [id] => 19
        [sort_order] => Sort 1
    )

[0] => Array
    (
        [name] => Name 1
    )

['1'] => Array
    (
        [id] => 19
        [sort_order] => Sort 2
    )

[1] => Array
    (
        [name] => Name 2
    )

['2'] => Array
    (
        [id] => 19
        [sort_order] => Sort 2
    )

[2] => Array
    (
        [name] => Name 3
    )

My function for insert

public function addFilterDamask($data) {
    foreach ($data['filter'] as $filter => $value) {
     $query =   $this->db->query("INSERT INTO `" . DB_PREFIX . "damask_name` SET name = '" . $value['name'] . "', sort_order = '" . (int)$value['sort_order'] . "', filter_id = '" . (int)$value['id'] . "'");
     }

}

Upvotes: 1

Views: 1046

Answers (1)

syntaqx
syntaqx

Reputation: 2866

Simplest way would be to check if MySQL has given it an ID yet, with the assumption you're using AUTO_INCREMENT:

$values = [
  [
    'id' => 1,
    'sort_order' => 1,
  ],
  [
    'sort_order' => 2,
  ],
];

foreach ($values as $i => $value) {
  if (array_key_exists('id', $value)) {
    // INSERT
    $values[$i]['id'] == ""; // result from ^
  } else {
    // UPDATE WHERE id == $value['id']
  }
}

Alternatively, if you're creating your IDs, you can look into REPLACE, which does what you'd like, but from MySQL's side.

FYI: Check out prepared statements - You should not be using the values directly like you are in PHP, as people can use SQL injection to change your intentions.

Upvotes: 1

Related Questions