사자자리

[PHP & MySQL] DELETE 본문

웹기초/생활코딩 WEB 3 - PHP & MySQL

[PHP & MySQL] DELETE

renne 2022. 8. 7. 21:15

1. index.php에 delete 버튼 생성하기

 - create와 update와 달리 입력 데이터 없이 바로 삭제하므로, process_delete.php로 id값을 전달만 한다.

<!--htdocs\index.php-->
<?php
//title을 목차로 만들기
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
$list = '';
while($row = mysqli_fetch_array($result)){
  $escaped_title = htmlspecialchars($row['title']);
  $list = $list."<li><a href=\"index.php?id={$row['id']}\">{$escaped_title}</a></li>";
}
//기본적인 상태
$article = array(
  'title'=>'Welcome',
  'description'=>'Hello, WEB'
);

$update_link = '';
$delete_link = '';
//id값이 있을 때, 즉 목차를 클릭했을 때
if(isset($_GET['id'])){
  $filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
  $sql = "SELECT * FROM topic WHERE id={$filtered_id}";
  $result = mysqli_query($conn, $sql);
  $row = mysqli_fetch_array($result);
  $article['title'] = htmlspecialchars($row['title']);
  $article['description'] = htmlspecialchars($row['description']);

  $update_link = '<a href="update.php?id='.$_GET['id'].'">update</a>';
  $delete_link = '
    <form action="process_delete.php" method="post">
      <input type="hidden" name="id" value="'.$_GET['id'].'">
      <input type="submit" value="delete">
    </form>
  ';
}
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>WEB</title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
      <?=$list?>
    </ol>
    <a href="create.php">create</a> <!--글쓰기 기능 링크-->
    <?=$update_link?> <!--수정하기 기능 링크-->
    <?=$delete_link?> <!--삭제하기 기능 링크-->
    <h2><?=$article['title']?></h2>
    <?=$article['description']?>
  </body>
</html>

 

2. process_delete.php 생성하기

<!--htdoc\process_delete.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
settype($_POST['id'], 'integer'); //$_POST['id'] 값 중 정수(integer)만 살린다.
$filtered = array(
  'id'=>mysqli_real_escape_string($conn, $_POST['id']),

);

$sql = "DELETE FROM topic WHERE id = {$filtered['id']}";

$result = mysqli_query($conn, $sql);

if($result === false){
  echo "ERROR";
  error_log(mysqli_query($conn));
}
else {
  echo '삭제에 성공했습니다. <a href="index.php">BACK TO HOMEPAGE</a>';
}
?>

 

3. 실습

MariaDB [opentutorials]> SELECT * FROM topic;
+----+------------+-------------------------------+---------------------+
| id | title      | description                   | created             |
+----+------------+-------------------------------+---------------------+
|  4 | MySQL      | MySQL but we're using MariaDB | 2022-08-01 23:23:34 |
|  5 | Oracle     | Oracle is ...                 | 2022-08-01 23:24:00 |
|  6 | SQL Server | SQL Server is ...             | 2022-08-01 23:24:17 |
|  7 | MongoDB    | MongoDB is ...                | 2022-08-01 23:24:31 |
+----+------------+-------------------------------+---------------------+
4 rows in set (0.000 sec)
Comments