2

My code so far:

$query = 'INSERT INTO articles(id, name, picture, url, origAmount, currAmount, added) VALUES ';

$insertQuery = array();
$insertData = array();

$date = getDate();

foreach ($articles as $article) {
    $insertQuery[] = '(?,?,?,?,?,?,?)';
    $insertData[] = $article->id;
    $insertData[] = $article->name;
    $insertData[] = $article->picture;
    $insertData[] = $article->url;
    $insertData[] = $article->amount;
    $insertData[] = $article->amount;
    $insertData[] = $date['year'] . '-' . $date['mon'] . '-' . $date['mday'];
}

if(!empty($insertQuery)) {          
    $query .= implode(', ', $insertQuery);
    $handle = $this->link->prepare($query);
    $handle->execute($insertData);
}

If the id already exists I want to update only currAmount. I have tried

$insertQuery[] = '(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE currAmount = (currAmount)';

which gives

'SQLSTATE[42000]: Syntax error or access violation: 1064 [...] near '('0192801635','The Renaissance A Ve' at line 1'

So the literal content of the row, it inserted fine on the empty table though, so it's not a problem with the content per se.

How can I do this?

EDIT: SOLVED IT

After the implode, added

$query .= ' ON DUPLICATE KEY UPDATE currAmount = VALUES(currAmount)';

Thanks everyone.

2 Answers2

0
... ON DUPLICATE KEY UPDATE currAmount=values(currAmount)

You forgot to add values keyword

UPDATE Full example:

$insertQuery[] = '(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE currAmount=values(currAmount)';

Alex Kapustin
  • 1,869
  • 12
  • 15
-1

DO something like this

foreach ($articles as $article) {
  $insertQuery = '(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE currAmount = (currAmount)';
  $insertData = $article->id;
  $insertData = $article->name;
  $insertData = $article->picture;
  $insertData = $article->url;
  $insertData = $article->amount;
  $insertData = $article->amount;
  $insertData = $date['year'] . '-' . $date['mon'] . '-' . $date['mday'];

  if(!empty($insertQuery)) {          
    $query .= implode(', ', $insertQuery);
    $handle = $this->link->prepare($query);
    $handle->execute($insertData);
  }
}
Anil Shrestha
  • 1,180
  • 11
  • 16