如何插入或更新多行 - PDO

I have a small problem with the request to the base of the PDO.

I want to insert or update fields in one request. I want insert a few records to DB, but if there are already 'file_name' fields with the selected name then just to update the other fields. Below paste my php code.

For example: I adding 5 records id_product (eg. 1) and various other fields. Example fields recived from the $_post:

(id_product, alt, file_name, main_photo)
1, xxx, 1_1, 0;
1, xxx, 1_2, 0;
1, xxx, 1_3, 1;

my PHP code:

$query = "INSERT INTO product_image (id_product, alt, file_name, main_photo) VALUES ";
        $part = array_fill(0, count($_POST['file_name']), "(?, ?, ?, ?)");
        $query .= implode(",", $part);
        $query .= " ON DUPLICATE KEY UPDATE alt=VALUES(alt), main_photo=VALUES(main_photo)";
        $stmt = $this->_db->prepare($query);

$j = 1;
            $im_null = 0;
            for ($i = 0; $i < count($_POST['file_name']); $i++) {
                $stmt->bindParam($j++, $_POST['id_product'], \PDO::PARAM_INT);
                $stmt->bindParam($j++, $_POST['alt'][$i], \PDO::PARAM_STR);
                $stmt->bindParam($j++, $profile->base64_to_jpeg($_POST['file_name'][$i], APP_ROOT . '/uploads/products/' . $_POST['id_product'] . '_' . $_POST['file_nr'][$i]), \PDO::PARAM_STR);
                ($_POST['main_photo'][$i] == 1) ? $stmt->bindParam($j++, $_POST['main_photo'][$i], \PDO::PARAM_INT) : $stmt->bindParam($j++, $im_null);
            }
            $stmt->execute();

In this query inserts works good, but doesn't update, which is the second part of the request.

Move $j = 1; inside loop as it is you keep on incrementing $j.

$im_null = 0;
for ($i = 0; $i < count($_POST['file_name']); $i++) {
    $j = 1;