我对PDO基础的请求有一个小问题。
我想在一个请求中插入或更新字段。我想在DB中插入一些记录,但如果已经有具有选定名称的"file_name"字段,则只更新其他字段。下面粘贴我的php代码。
例如:我添加了5个记录id_product(例如1)和各种其他字段。从$_post:接收的示例字段
(id_product, alt, file_name, main_photo)
1, xxx, 1_1, 0;
1, xxx, 1_2, 0;
1, xxx, 1_3, 1;
我的PHP代码:
$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();
在这个查询中,插入操作很好,但不会更新,这是请求的第二部分。
在循环内移动$j = 1;
,保持$j
递增。
$im_null = 0;
for ($i = 0; $i < count($_POST['file_name']); $i++) {
$j = 1;