2012-06-15 2 views
0

PHP에서 기본 PHP 폼 (몇 개의 필드와 2 개의 체크 박스, 나중에 체크 박스를 추가하고 싶지만, 지금은 테스트 용으로 2 개만 사용하고 있습니다)이 있습니다. 필드와 체크 박스는 MySQL 데이터베이스에 저장되며 잘 작동합니다.MySQL 및 PHP를 기반으로 한 체크 박스 체크 상태

필자는 원래의 입력 양식을 반영하는 '편집'양식을 사용합니다. 단, 필드 값은 꽤 표준 인 행 ID를 기반으로 MySQL 데이터베이스에서로드됩니다.

현재 문제는 편집 양식의 마지막 필드가 다른 텍스트 입력 필드에 불과하다는 것입니다. 내가 뭘하고 싶은지는 원래 양식의 입력을 기반으로 선택되거나 선택 취소되는 확인란의 변경입니다.

ischecked을 사용해야 할 필요가 있다고 생각하지만 원본 양식의 논리를 변경해야하는지 또는 데이터베이스 자체를 변경해야하는지 확실하지 않습니다 (희망하지 않습니다!).

데이터베이스는 thusly 히 배치되어

------------------------------------------------------------------------------------------- 
| ID (int) | ARTICLEAUTHOR (varchar) | ARTICLEORGANIZATION (varchar) | ARTICLETAGS (varchar)| 
------------------------------------------------------------------------------------------- 

그리고 두 가지 형태의 코드는 다음과 같습니다.

첫째, 새 항목 양식 :

  // addnew.php 

      <?php 
      function renderForm($articletitle, $articleorganization, $articledate, $articleurl, $articletags) 
      . . . 
      </head> 

      <body> 
      . . . 
        <form id="form" name="form" action="" method="post"> 
        <h1>Create a new entry in the database</h1> 
        <table width="100%" border="0" cellpadding="6"> 
         <tr> 
         <td colspan="2"><legend>Article details</legend></td> 
         </tr> 
         <tr> 
         <td width="20%" align="right"><span class="field">Article Title:</span></td> 
         <td width="80%" align="left"><span class="field"> 
          <input name="articletitle" type="text" value="<?php echo $articletitle; ?>" size="50"/> 
         </span></td> 
         </tr> 
         <tr> 
         <td align="right"><span class="field">Article Author:</span></td> 
         <td align="left"><span class="field"> 
          <input name="articleorganization" type="text" value="<?php echo $articleorganization; ?>" size="50"/> 
         </span></td> 
         </tr> 
         <tr> 
         <td align="right"><span class="field">Article Date:</span></td> 
         <td align="left"><span class="field"> 
          <input name="articledate" type="text" value="<?php echo $articledate; ?>" size="50"/> 
         </span></td> 
         </tr> 
         <tr> 
         <td align="right"><span class="field">Article URL:</span></td> 
         <td align="left"><span class="field"> 
         <input name="articleurl" type="text" value="<?php echo $articleurl; ?>" size="50"/> 
         </span></td> 
         </tr> 
        </table> 
      . . . 
         <input type="checkbox" name="articletags[]" value="checkbox" id="articletags_0" /> 
         <input type="checkbox" name="articletags[]" value="checkbox 2" id="articletags_1" /> 

         </div> 
        </fieldset> 
        <footer><input type="submit" name="submit" value="Add this Article"></footer> 
      . . . 
        </form> 
       </div> 
       </div> 
      . . . 
      </body> 
      </html> 
      <?php 
      } 

      // connect to the database 
      include('settings.php'); 

      if(count($articletags) > 0) 
      { 
      $articletags_string = implode(",", $articletags); 
      } 
      // check if the form has been submitted. If it has, start to process the form and save it to the database 
      if($_SERVER['REQUEST_METHOD'] == 'POST') 
      { 
      // get form data, making sure it is valid 
      $articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle'])); 
      $articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization'])); 
      $articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate'])); 
      $articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl'])); 
      $articletags = implode(',', $_POST['articletags']); 

      . . . 

      mysql_query("INSERT articles SET articletitle='$articletitle', articleorganization='$articleorganization', articledate='$articledate', articleurl='$articleurl', articletags='$articletags' ") 
      or die(mysql_error()); 

      // once saved, redirect to success page 
      header("Location:addsuccess.php"); 
      } 
      } 
      else 
      // if the form hasn't been submitted, display the form 
      { 
      renderForm('','','',''); 
      } 
      ?> 

이제 편집 양식 :

  <?php 
      . . . 
      function renderForm($id, $articletitle, $articleorganization, $articledate, $articleurl, $articletags) 
      { 
      ?> 
      . . . 
       <div class="content"> 
       <div id="stylized" class="myform"> 
        <form id="form" name="form" action="" method="post"> 
        <input type="hidden" name="id" value="<?php echo $id; ?>"/> 
        <h1>Edit Details for &nbsp; &nbsp;<?php echo $articletitle; ?></h1> 
        <table width="100%" border="0" cellpadding="6"> 
         <tr align="center" valign="middle"> 
         <td colspan="2"><legend>Article details</legend></td> 
         </tr> 
         <tr> 
         <td width="26%" align="right"><span class="field">Article Title</span></td> 
         <td width="74%" align="left"><span class="field"> 
          <input name="articletitle" type="text" value="<?php echo $articletitle; ?>" size="50"/> 
         </span></td> 
         </tr> 
         <tr> 
         <td align="right"><span class="field">Article Author</span></td> 
         <td align="left"><span class="field"> 
          <input name="articleorganization" type="text" value="<?php echo $articleorganization; ?>" size="50"/> 
         </span></td> 
         </tr> 
         <tr> 
         <td align="right"><span class="field">Article Date</span></td> 
         <td align="left"><span class="field"> 
          <input name="articledate" type="text" value="<?php echo $articledate; ?>" size="50"/> 
         </span></td> 
         </tr> 
         <tr> 
         <td align="right"><span class="field">Article Url:</span></td> 
         <td align="left"><span class="field"> 
          <input name="articleurl" type="text" value="<?php echo $articleurl; ?>" size="50"/> 
         </span></td> 
         </tr> 
         <tr> 
         <td align="right"><span class="field">Article Tags:</span></td> 
         <td align="left"><span class="field"> 
          <input name="articletags" type="text" value="<?php echo $articletags; ?>" size="50"/> 
         </span></td> 
         </tr> 
         <tr align="center" valign="middle"> 
         <td colspan="2"><input type="submit" name="submit" value="Submit" /></td> 
         </tr> 
        </table> 
      . . . 
        </fieldset> 
        <footer></footer></form> 
       </div> 
       </div> 
       <div class="footer"> 
      . . . 
       <!-- end .footer --></div> 
      </body> 
      </html> 
      <?php 
      } 



      // connect to the database 
      include('settings.php'); 

      // check if the form has been submitted. If it has, process the form and save it to the database 
      if (isset($_POST['submit'])) 
      { 
      // confirm that the 'id' value is a valid integer before getting the form data 
      if (is_numeric($_POST['id'])) 
      { 
      // get form data, making sure it is valid 
      $id = $_POST['id']; 
      $articletitle = mysql_real_escape_string(htmlspecialchars($_POST['articletitle'])); 
      $articleorganization = mysql_real_escape_string(htmlspecialchars($_POST['articleorganization'])); 
      $articledate = mysql_real_escape_string(htmlspecialchars($_POST['articledate'])); 
      $articleurl = mysql_real_escape_string(htmlspecialchars($_POST['articleurl'])); 
      $articletags = mysql_real_escape_string(htmlspecialchars($_POST['articletags'])); 

      . . . 

      mysql_query("UPDATE articles SET articletitle='$articletitle', articleorganization='$articleorganization', articledate='$articledate', articleurl='$articleurl', articletags='$articletags' WHERE id=$id") 
      or die(mysql_error()); 

      . . . 
      { 

      // get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0) 
      if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) 
      { 
      // query db 
      $id = $_GET['id']; 
      $result = mysql_query("SELECT * FROM articles WHERE id=$id") 
      or die(mysql_error()); 
      $row = mysql_fetch_array($result); 

      // check that the 'id' matches up with a row in the databse 
      if($row) 
      { 

      // get data from db 
      $articletitle = $row['articletitle']; 
      $articleorganization = $row['articleorganization']; 
      $articledate = $row['articledate']; 
      $articleurl = $row['articleurl']; 
      $articletags = $row['articletags']; 

      // show form 
      renderForm($id, $articletitle, $articleorganization, $articledate, $articleurl, $articletags, ''); 
      } 
      . . . 
      ?> 
+0

일반적으로 양식의 확인란은 데이터베이스의 부울 값과 연결됩니다. 코드에서 articletags 필드와 연관된 체크 박스를 사용하려는 것처럼 보입니다. 그게 맞습니까? – mwotton

+0

네, 맞습니다. @mwotton. – Zrb0529

답변

1

당신은 태그를 추적하기 위해 두 개의 새 테이블을 가지고 더 나을 것입니다.

다음과 같은 구조로 태그 필드를

태그 테이블을 잃게 당신의 기사 테이블 : 당신이 기반 확인란을 구축

ArticleHasTags 
---- 
article_id (int) 
tag_id (int) 

그런

Tags Table 
----- 
id (int) 
tagname varchar(64) 

ArticleHasTags crossmap 테이블에 다음과 같은 구조 태그 테이블 항목. 기사를 저장할 때 항목 양식의 확인란을 기반으로 ArticleHasTags 테이블에 항목을 추가 할 수도 있습니다.

편집 양식을 표시 할 때, 당신은 제 테이블과 ArticleHasTags 테이블 모두에서 데이터를 가져, 중 여러 조인 또는 두 번째 선택하고 작업을 수행하는 것이 더 쉬울 수 있습니다

select * from ArticleHasTags where article_id = $id 

(여기서 $ id를

그런 다음 태그 데이터베이스의 모든 행을 다시 가져 와서 확인란을 표시합니다. 각 확인란을 표시 할 때 in_array()를 사용하여 검색 한 ArticleHasTag 결과에 대해 태그 ID를 확인하여 기사에 해당 태그가 있는지 확인할 수 있습니다. ,

이 모두 매우 절차입니다)

나는 그러나 내가이 포인터를 사용하고 자신에서 세부 사항을 파악하기 위해 장기적으로 당신에게 더 가치가있을 것으로 판단 것, 더 깊이 들어갈 수 있습니다 그러나 후회하지 않고서는 기존 코드를 사용하는 수준과 비슷합니다. 격려하고 계속 배우십시오! 당신은 올바른 자리에 왔습니다.

+0

이것은 흥미로운 일입니다. 하지만 추가 복잡성이 좋지 않다고 생각했을까요? 실베스터 스탤론 (Sylvester Stallone)이 쓴 두 기사 (제목 1과 제목 2)는 모두 "역도지기"로 표기되어 있지만 첫 번째 표제는 "자유 가중치"로 표기되어 있고 두 번째 표제는 " 무게 기계 "다음이 구조, 검색 능력의 관점에서 복잡성을 추가하지 않을까요? – Zrb0529