본문 바로가기
PHP

Updating data - category

by 영감은어디에 2024. 10. 12.

category list (categories)

$sql = "SELECT id, name FROM category;"; 
$categories = pdo($pdo, $sql)->fetchAll();

<h1>Categories</h1>
<p><a href="category.php" class="btn btn-primary">+ NEW</a></p>

<table class="categories">
<tr>
    <th>Name</th>
    <th class="edit">Edit</th>
    <th class="del">Delete</th>
</tr>
<?php foreach ($categories as $category) { ?>
<tr>
    <td><?= html_escape($category['name']) ?></td>
    <td><a href="category.php?id=<?= $category['id'] ?>">Edit</a></td>
    <td><a href="category-delete.php?id=<?= $category['id'] ?>">Delete</a></td>
</tr>
<?php } ?>
</table>

category delete

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); 
$category = ''; 
if (!$id) {  
    redirect('categories.php', ['failure' => 'Category not found']); 
}

$sql = "SELECT name FROM category WHERE id = :id;";
$category = pdo($pdo, $sql, [$id])->fetchColumn(); 
if (!$category) {
    redirect('categories.php', ['failure' => 'Category not found']); 
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {  
    try { 
        $sql = "DELETE FROM category WHERE id = :id;";
        pdo($pdo, $sql, [$id]);  
        redirect('categories.php', ['success' => 'Category deleted']);
    } catch (PDOException $e) { 
        if ($e->errorInfo[1] === 1451) {  //제약
            redirect('categories.php', ['failure' => 'Category contains articles that 
            must be moved or deleted before you can delete it']); /
        } else {   
            throw $e; 
        }
    }
}
<form action="category-delete.php?id=<?= $id ?>" method="POST" >
 <p>Click confirm to delete the category: <?= html_escape($category) ?></p>
 <input type="submit" name="delete" value="Confirm">
 <a href="categories.php">Cancel</a>
</form>

category new, update 

// 변수초기화
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); 
$category = [
    'id'          => $id,
    'name'        => '',
    'description' => '',
    'navigation'  => false,
];              
$errors = [
    'warning'     => '',
    'name'        => '',
    'description' => '',
];   

// 아이디 있으면 편집모드
if ($id) {    
    $sql = "SELECT id, name, description, navigation 
              FROM category 
             WHERE id = :id;";   
    $category = pdo($pdo, $sql, [$id])->fetch(); 

    if (!$category) {   
        redirect('categories.php', ['failure' => 'Category not found']); 
    }
}

// 유효성 검사 
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $category['name']        = $_POST['name']; 
    $category['description'] = $_POST['description']; 
    $category['navigation']  = (isset($_POST['navigation']) and ($_POST['navigation'] == 1)) ? 1 : 0; 

    // 유효하지 않다면 에러 
    $errors['name']          = (is_text($category['name'], 1, 24))
        ? '' : 'Name should be 1-24 characters.'; 
    $errors['description']   = (is_text($category['description'], 1, 254))
        ? '' : 'Description should be 1-254 characters.'; 

    $invalid = implode($errors); 

    // 유효하다면 업데이트 
    if ($invalid) {      
        $errors['warning'] = 'Please correct errors'; 
    } else { 
        $arguments = $category; 
        if ($id) { 
            $sql = "UPDATE category 
                       SET name = :name, description = :description, 
                           navigation = :navigation 
                     WHERE id = :id;"; 
        } else {    
            unset($arguments['id']); //아이디가 없으면 새글, 카테고리에서 아이디 제거
            $sql = "INSERT INTO category (name, description, navigation) 
                         VALUES (:name, :description, :navigation);";//카테고리 생성
        }

        try {   
            pdo($pdo, $sql, $arguments);     //실행 
            redirect('categories.php', ['success' => 'Category saved']); 
        } catch (PDOException $e) {  
            if ($e->errorInfo[1] === 1062) {  //고유성 제약이면 
                $errors['warning'] = 'Category name already in use';
            } else {                                  
                throw $e;      
            }
        }
    }
}
<form action="category.php?id=<?= $id ?>" method="post">
    <h1>Edit Category</h1>
    <?php if ($errors['warning']) { ?>
    <?= $errors['warning'] ?>
    <?php } ?>

    <label for="name">Name: </label>
    <input type="text" name="name" id="name"
            value="<?= html_escape($category['name']) ?>">
    <span class="errors"><?= $errors['name'] ?></span>

    <label for="description">Description: </label>
    <textarea name="description" id="description"
               ><?= html_escape($category['description']) ?></textarea>
    <span class="errors"><?= $errors['description'] ?></span>

    <input type="checkbox" name="navigation" id="navigation" value="1"
        <?= ($category['navigation'] === 1) ? 'checked' : '' ?>>
    <label for="navigation">내비에 보이기</label>

    <input type="submit" value="Save">
</form>

'PHP' 카테고리의 다른 글

Updating data - article  (0) 2024.10.12
getting data  (0) 2024.10.11
sql  (0) 2024.10.11
date  (0) 2024.10.10
image file  (0) 2024.10.10
form  (0) 2024.10.10
내장함수, number, update  (0) 2024.10.10
object  (0) 2024.10.09