사자자리

[PHP & MySQL] 새로운 테이블(author) - 읽기, 생성, 수정, 삭제 본문

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

[PHP & MySQL] 새로운 테이블(author) - 읽기, 생성, 수정, 삭제

renne 2022. 8. 8. 23:04

읽기

1. author.php 생성하기

2. <table>, <tr>, <td> 태그를 이용하여 표 형식으로 내용 출력하기

<!--htdocs\author.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>WEB</title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <p><a href="index.php">topic</a></p>

    <!--표-->
    <table border="1">
      <tr> <!--같은 행을 그룹핑하는 태그-->
        <td>id</td><td>name</td><td>profile</td>  <!--열을 만드는 태그-->
        <?php
        $sql = "SELECT * FROM author";
        $result = mysqli_query($conn, $sql);
        while($row = mysqli_fetch_array($result)){
          $filtered = array(
            'id'=>htmlspecialchars($row['id']),
            'name'=>htmlspecialchars($row['name']),
            'profile'=>htmlspecialchars($row['profile'])
          )
          ?>
          <tr>
            <td><?=$filtered['id']?></td>
            <td><?=$filtered['name']?></td>
            <td><?=$filtered['profile']?></td>
          </tr>
          <?php
        }
        ?>
      </tr>
    </table>
    
  </body>
</html>

 


생성

1. author.php에 <form>, <input>, <textarea> 태그로 Create Author 기능 만들기

<!--htdocs\author.php-->
(생략)
    </table>
    
    <!--Create-->
    <form action="process_create_author.php" method="post">
      <p><input type="text" name="name" placeholder="name"></p>
      <p><textarea name="profile" placeholder="profile"></textarea></p>
      <p><input type="submit" value="Create Author"></p>
    </form>
  </body>
</html>

 

2. process_create_author.php에 전송된 데이터를 sql문을 통해 DB에 전달하기

<!--htdoc\process_create_author.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
$filtered = array(
  'name'=>mysqli_real_escape_string($conn, $_POST['name']),
  'profile'=>mysqli_real_escape_string($conn, $_POST['profile'])
);

$sql="
  INSERT INTO author(name, profile)
  VALUES('{$filtered['name']}', '{$filtered['profile']}')
";
$result = mysqli_query($conn, $sql);

if($result === false){
  echo "ERROR";
  error_log(mysqli_query($conn));
}
else {
  echo "성공했습니다.\n<a href=\"author.php\">BACK TO PAGE</a>";
}
?>

 

3. 실습

 

 


수정

1. author.php의 표에 새로운 열을 추가하고, update 링크를 넣는다.

2. update 링크를 클릭하면 데이터들이 process_update_author.php로 전송된다.

<!--htdocs\author.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>WEB</title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <p><a href="index.php">topic</a></p>

    <!--표-->
    <table border="1">
      <tr> <!--같은 행을 그룹핑하는 태그-->
        <td>id</td><td>name</td><td>profile</td><td></td>  <!--열을 만드는 태그-->
        <?php
        $sql = "SELECT * FROM author";
        $result = mysqli_query($conn, $sql);
        while($row = mysqli_fetch_array($result)){
          $filtered = array(
            'id'=>htmlspecialchars($row['id']),
            'name'=>htmlspecialchars($row['name']),
            'profile'=>htmlspecialchars($row['profile'])
          )
          ?>
          <tr>
            <td><?=$filtered['id']?></td>
            <td><?=$filtered['name']?></td>
            <td><?=$filtered['profile']?></td>
            <td><a href="author.php?id=<?=$filtered['id']?>">update</a></td>
          </tr>
          <?php
        }
        ?>
      </tr>
    </table>
    <?php
    //일반적인 상황일 때, 즉 update를 클릭하지 않았을 때
    $escaped = array(
      'name'=>'',
      'profile'=>''
    );
    $label_submit = 'Create Author';  //submit 버튼의 value
    $form_action = 'process_create_author.php';
    $form_id = '';
    //id값이 있을 때, 즉 update를 클릭했을 때
    if(isset($_GET['id'])){
      $filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
      settype($filtered_id, 'integer');
      $sql = "SELECT * FROM author WHERE id = {$filtered_id}";
      $result = mysqli_query($conn, $sql);
      $row = mysqli_fetch_array($result);
      $escaped['name'] = htmlspecialchars($row['name']);
      $escaped['profile'] = htmlspecialchars($row['profile']);
      $label_submit = 'Update Author';
      $form_action = 'process_update_author.php';
      $form_id = '<input type="hidden" name="id" value="'.$_GET['id'].'">';
    }
    ?>

    <!--Create-->
    <form action="<?=$form_action?>" method="post">
      <?=$form_id?>
      <p><input type="text" name="name" placeholder="name" value="<?=$escaped['name']?>"></p>
      <p><textarea name="profile" placeholder="profile"><?=$escaped['profile']?></textarea></p>
      <p><input type="submit" value="<?=$label_submit?>"></p>
    </form>
  </body>
</html>

 

3. process_update_author.php에서 sql문을 통해 DB를 UPDATE한다.

<!--htdoc\process_update_author.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']),
  'name'=>mysqli_real_escape_string($conn, $_POST['name']),
  'profile'=>mysqli_real_escape_string($conn, $_POST['profile'])
);

$sql="
  UPDATE author
  SET name = '{$filtered['name']}', profile = '{$filtered['profile']}'
  WHERE id = {$filtered['id']}
";
$result = mysqli_query($conn, $sql);

if($result === false){
  echo "ERROR";
  error_log(mysqli_query($conn));
}
else {
  header('Location: author.php?='.$filtered['id']);
}
?>

 

4. 실습

 

 


삭제

1. author.php

 - 표에 delete 버튼을 담을 열을 추가한다.

 - delete 버튼을 누르면 confirm 함수로 인해 Really? 창이 뜨고, OK를 누르면 true값이 return된다.

 - true값이 return되면, id 값이 process_delete_author.php로 전송된다.

<!--htdocs\author.php-->
<?php
$conn = mysqli_connect('localhost', 'root', '021103', 'opentutorials');
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>WEB</title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <p><a href="index.php">topic</a></p>

    <!--표-->
    <table border="1">
      <tr> <!--같은 행을 그룹핑하는 태그-->
        <td>id</td><td>name</td><td>profile</td><td></td>  <!--열을 만드는 태그-->
        <?php
        $sql = "SELECT * FROM author";
        $result = mysqli_query($conn, $sql);
        while($row = mysqli_fetch_array($result)){
          $filtered = array(
            'id'=>htmlspecialchars($row['id']),
            'name'=>htmlspecialchars($row['name']),
            'profile'=>htmlspecialchars($row['profile'])
          )
          ?>
          <tr>
            <td><?=$filtered['id']?></td>
            <td><?=$filtered['name']?></td>
            <td><?=$filtered['profile']?></td>
            <td><a href="author.php?id=<?=$filtered['id']?>">update</a></td>
            <td>
              <form action="process_delete_author.php" method="post" onsubmit="if(!confirm('Really?')){return false};">
                <input type="hidden" name="id" value="<?=$filtered['id']?>">
                <input type="submit" value="delete">
              </form>
            </td>
          </tr>
          <?php
        }
        ?>
      </tr>
    </table>

    <?php
    //일반적인 상황일 때, 즉 update를 클릭하지 않았을 때
    $escaped = array(
      'name'=>'',
      'profile'=>''
    );
    $label_submit = 'Create Author';  //submit 버튼의 value
    $form_action = 'process_create_author.php';
    $form_id = '';
    //id값이 있을 때, 즉 update를 클릭했을 때
    if(isset($_GET['id'])){
      $filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
      settype($filtered_id, 'integer');
      $sql = "SELECT * FROM author WHERE id = {$filtered_id}";
      $result = mysqli_query($conn, $sql);
      $row = mysqli_fetch_array($result);
      $escaped['name'] = htmlspecialchars($row['name']);
      $escaped['profile'] = htmlspecialchars($row['profile']);
      $label_submit = 'Update Author';
      $form_action = 'process_update_author.php';
      $form_id = '<input type="hidden" name="id" value="'.$_GET['id'].'">';
    }
    ?>

    <!--Create-->
    <form action="<?=$form_action?>" method="post">
      <?=$form_id?>
      <p><input type="text" name="name" placeholder="name" value="<?=$escaped['name']?>"></p>
      <p><textarea name="profile" placeholder="profile"><?=$escaped['profile']?></textarea></p>
      <p><input type="submit" value="<?=$label_submit?>"></p>
    </form>
  </body>
</html>

 

2. process_delete_author.php

 - 전달받은 id 값을 sql문에 사용한다.

 - 첫 번째 sql문: author_id 값이 id 값과 일치하는 topic 테이블의 행을 지운다.

 - 두 번째 sql문: id 값에 해당하는 author 테이블의 행을 지운다.

<!--htdoc\process_delete_author.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 author_id = {$filtered['id']}";
mysqli_query($conn, $sql);

$sql = "DELETE FROM author WHERE id = {$filtered['id']}";
$result = mysqli_query($conn, $sql);

if($result === false){
  echo "ERROR";
  error_log(mysqli_query($conn));
}
else {
  header('Location: author.php');
}
?>

 

3. 실습

 - Luna 삭제

 

 - Luna가 author였던 topic 테이블의 데이터도 삭제되었다.

MariaDB [opentutorials]> SELECT * FROM topic;	#author_id에 3이 없음
+----+------------+-------------------+---------------------+-----------+
| id | title      | description       | created             | author_id |
+----+------------+-------------------+---------------------+-----------+
|  4 | MySQL      | MySQL is ...      | 2022-08-01 23:23:34 |         1 |
|  5 | Oracle     | Oracle is ...     | 2022-08-01 23:24:00 |         1 |
|  6 | SQL Server | SQL Server is ... | 2022-08-01 23:24:17 |         2 |
|  7 | MongoDB    | MongoDB is ...    | 2022-08-01 23:24:31 |         2 |
| 15 | OrientDB   | OrientDB is ...   | 2022-08-07 23:57:54 |         1 |
+----+------------+-------------------+---------------------+-----------+
5 rows in set (0.001 sec)

 

Comments