티스토리 뷰

반응형

ajax로 비동기식 저장할때,

마지막 레코드 번호를 가져오고 싶을때 이방법이 아니면 코드가 길어집니다.

개발에 필요한 코드인데, 기록으로 남겨둡니다.

else if ($mode == "insert" || $mode == '' || $mode == null) {
    $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " " . $update_log . "&#10";
    // 데이터 삽입
    try {
        $pdo->beginTransaction();

        // SQL 쿼리 생성 (삽입)
        $sql = "INSERT INTO " . $DB . "." . $tablename . " (";
        $sql .= "reg_date, check_type, author, remark, update_log, search_tag, ";
        $sql .= "front_bottom_width, rail_width, box_width, box_height ";
        $sql .= ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmh = $pdo->prepare($sql);

        // 변수 바인딩
        $stmh->bindValue(1, $reg_date, PDO::PARAM_STR);
        $stmh->bindValue(2, $check_type, PDO::PARAM_STR);
        $stmh->bindValue(3, $author, PDO::PARAM_STR);
        $stmh->bindValue(4, $remark, PDO::PARAM_STR);
        $stmh->bindValue(5, $update_log, PDO::PARAM_STR);
        $stmh->bindValue(6, $search_tag, PDO::PARAM_STR);
        $stmh->bindValue(7, $front_bottom_width, PDO::PARAM_STR);
        $stmh->bindValue(8, $rail_width, PDO::PARAM_STR);
        $stmh->bindValue(9, $box_width, PDO::PARAM_STR);
        $stmh->bindValue(10, $box_height, PDO::PARAM_STR);

        // 실행
        $stmh->execute();
        
        // 삽입된 마지막 ID를 가져오기
        $num = $pdo->lastInsertId();
        $pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        print "오류: " . $Exception->getMessage();
    }
}

else if ($mode == "delete") { // 데이터 삭제
    try {
        $pdo->beginTransaction();
        $sql = "UPDATE " .  $DB . "." . $tablename . " SET is_deleted=1 WHERE num = ?";  
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);      
        $stmh->execute();
        $pdo->commit();
    } catch (PDOException $ex) {
        $pdo->rollBack();
        print "오류: ".$ex->getMessage();
    }
}

$data = [   
 'num' => $num,
 'mode' => $mode
]; 

echo json_encode($data, JSON_UNESCAPED_UNICODE);

?>

반응형
댓글