简体   繁体   中英

check specific cols then, update or create a new row, pdo

Trying to check specific column values before inserting a new row. But a bit confused PDO's ON DUPLICATE KEY UPDATE so, here is insert function below.

public function insert_schedule($user_id, $status, $content, $date, $time, $remarks, $created_at){
    $sql = "INSERT INTO schedules (user_id, status, content, return_date, return_time, remarks, created_at) VALUES (?,?,?,?,?,?,?) 
    ON DUPLICATE KEY UPDATE user_id, created_at = VALUES(user_id, created_at)";
    $stmt = $this->connect()->prepare($sql);
    $stmt->execute([$user_id, $status, $content, $date, $time, $remarks, $created_at]); 
}   

I want to check created_at and user_id before insert a new row. if created_at already exist on same user_id than update that row. else, insert a new row. How can I fix the above function.

Change the query to:

INSERT INTO schedules SET user_id=?, status=?, content=?, return_date=?, return_time=?, remarks=?, created_at=?
ON DUPLICATE KEY UPDATE status=?, content=?, return_date=?, return_time=?, remarks=?
$stmt->execute([
    $user_id, $status, $content, $date, $time, $remarks, $created_at,
    $status, $content, $date, $time, $remarks
]);
  • Duplicate keys must definded as index.
  • Execute needs the values as duplicate keys AGAIN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM