Pregunta

I have this code that insert mulitple rows in one query which works.

What I would like it to do no is if colA already exists in the database update colB.

I've looked at using INSERT ON DUPLICATE KEY UPDATE but I can only see it working for one row at a time where I could have 1000 rows.

How can i use the INSERT/UPDATE on my code?

$sql = 'INSERT INTO table (colA, colB, colC, colD, colE) VALUES';
$insertQuery = array();
$insertData = array();
$n = 0;
// and loop through the array binding values from each row
// to the placeholders before execution
// placeholders names increment starting at 0 to array length
foreach ($rows as $row) {
    $insertQuery[] = '(
        :colA' . $n . ',
        :colB' . $n . ',
        :colC' . $n . ',
        :colD' . $n . ',
        :colE' . $n . '
    )';

    $insertData['colA' . $n] = $row['colA'];
    $insertData['colB' . $n] = $row['colB'];
    $insertData['colC' . $n] = $row['colC'];
    $insertData['colD' . $n] = $row['colD'];
    $insertData['colE' . $n] = $row['load_note'];
    $insertData['last_updated' . $n] = $row['colE'];
    $n++;
}

// prepare the query and exeute it
if (!empty($insertQuery)) {
    $sql .= implode(', ', $insertQuery);
    $stmt = $db->prepare($sql);
    $stmt->execute($insertData);
}

EDIT:

How do I update multiple columns? Is this correct?

$sql .= " ON DUPLICATE KEY UPDATE status = VALUES(colB, colC)";

EDIT2:

I added this but i get no rows inserting (empty table)

$sql .= " ON DUPLICATE KEY UPDATE colA = VALUES(colA), 
                  colB = VALUES(colB), 
                  colC = VALUES(colC), 
                  colD = VALUES(colD), 
                  colE = VALUES(colE))";
¿Fue útil?

Solución

After the implode() call, add:

$sql .= " ON DUPLICATE KEY UPDATE colB = VALUES(colB)";

Assuming colA has a unique key, then whenever that column already exists, this will set colB to the new colB from that row of the INSERT, and leave all the other columns unchanged.

http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

It has the following example that shows that each duplicate row is handled independently.

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
  ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

That statement is identical to the following two statements:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=3;
INSERT INTO table (a,b,c) VALUES (4,5,6)
  ON DUPLICATE KEY UPDATE c=9;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top