2014-06-07 3 views
1

PHP 코드로 mySQL 데이터베이스에서 두 개의 다른 테이블을 업데이트하려고합니다. 하나의 블록은 완벽하게 작동하지만 "if (isset ...")에서 "데이터베이스를 쿼리하는 중 오류가 발생했습니다"메시지가 표시되므로 배열 값 (체크 상자)을 추가하려는 코드가 작동하지 않습니다. ?여러 값으로 두 개의 서로 다른 테이블을 삽입/업데이트하려고 시도했습니다.

EDIT.PHP

<h3>Edit Profile: <?php echo $_REQUEST['first_name'];?></h3> 
    <form enctype="multipart/form-data" method="POST" action="change.php"> 
    <table border="0" width="60%"> 

    <tr><td width="30%">First Name: </td><td><input type="text" 
    name="upd_first_name" value="<?php echo $_REQUEST['first_name'];?>" maxlength="20"> </td></tr> 

    <tr><td width="30%">Last Name: </td><td><input type="text" 
    name="upd_last_name" value="<?php echo $_REQUEST['last_name'];?>" maxlength="20"> </td></tr> 

    <tr><td width="30%">Email: </td><td><input type="text" 
    name="upd_email" value="<?php echo $_REQUEST['email'];?>" maxlength="45"> </td></tr> 

    <tr><td width="30%">Password: </td><td><input type="password" 
    name="upd_password" id="upd_password" value="<?php echo $_REQUEST['password'];?>" maxlength="20"> </td></tr> 

    <tr><td width="30%">Confirm Password: </td><td><input type="password" 
    name="upd_cpassword" id="upd_cpassword" value="<?php echo $_REQUEST['password'];?>" maxlength="20" onkeyup="checkPass(); return false;"> </td></tr> 

    <tr><td width="30%">Profile Visbility: </td><td><input type="radio" name="upd_profilevis" value="1" id="1" checked> Private <input type="radio" name="upd_profilevis" value="2" id="2" > Public </td></tr> 

    <<tr><td width="30%">Industries: </td><td> 
    <input type="checkbox" name="industries[]" value="1"/>None</br> 
    <input type="checkbox" name="industries[]" value="2"/>Film</br> 
    <input type="checkbox" name="industries[]" value="3"/>Television</br> 
    <input type="checkbox" name="industries[]" value="4"/>Music</br> 
    <input type="checkbox" name="industries[]" value="5"/>Gaming</br> 
    <input type="checkbox" name="industries[]" value="6"/>Books</br> 
    <input type="checkbox" name="industries[]" value="7"/>Comic Books</br> 
    </td></tr> 

    <tr><td width="30%">Link: </td><td><input type="text" 
    name="upd_link" value="<?php echo $_REQUEST['profile_link'];?>" maxlength="45"> </td></tr> 

    <tr><td width="30%">Bio: </td><td><input type="text" 
    name="upd_bio" value="<?php echo $_REQUEST['bio'];?>" maxlength="500"> </td></tr> 

    <input type="hidden" name="MAX_FILE_SIZE" value="10000000"> 
    <tr><td width="30%">Picture: </td><td><input type="file" id="image" name="image"></tr> 
    </table> 
    <span id="confirmMessage" class="confirmMessage"></span><br /> 

    <input type="submit" value="Save & Update"/> 
    <input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>"> 
    </form> 

CHANGE.PHP을보고

<?php 
//pulls data/files from the edit.php form 
$id= $_REQUEST['id']; 
$upd_first_name= $_REQUEST['upd_first_name']; 
$upd_last_name= $_REQUEST['upd_last_name']; 
$upd_email= $_REQUEST['upd_email']; 
$upd_password= $_REQUEST['upd_password']; 
$upd_cpassword= $_REQUEST['upd_cpassword']; 
$upd_profilevis= $_REQUEST['upd_profilevis']; 
$upd_link= $_REQUEST['upd_link']; 
$upd_bio= $_REQUEST['upd_bio']; 
$mypic = $_FILES['image']['name']; 
$temp = $_FILES['image']['tmp_name']; 
$type = $_FILES['image']['type']; 


//checks if the picture is of the right type before inserting 
if(($type=="image/jpeg") || ($type=="image/jpg") || ($type=="image/png") || ($type=="image/bmp") || ($type=="image/gif")) { 

    //connects to the database 
    $dbc = mysqli_connect('localhost', 'root', 'root', 'profile') or die('Error connecting to MySQL server.'); 

    //if industries are selected on the form edit.php insert into table 
    //each industry assigned to the member ID (junction table) 
     if(isset($_POST['industries'])) { 

      //deletes from table current values 
      $query = "DELETE FROM `industry_has_member` WHERE member_idmember='$id'"; 
      $result = mysqli_query($dbc, $query) or die(mysqli_error($dbc)); 
      //to report errors 
      if(!$result) 
       { 
       printf("Errormessage: %s\n", mysqli_error($dbc)); 
       } 
      //adds on table new values 
      foreach ($_POST['industries'] as $industry) { 
      $query = "INSERT INTO industry_has_member (industry_idindustry, member_idmember) values ('$industry', '$id')"; 
      $result = mysqli_query($dbc, $query) or die(mysqli_error($dbc)); 
      //to report errors 
      if(!$result) 
       { 
       printf("Errormessage: %s\n", mysqli_error($dbc)); 
       } 
      } 
     } 

    $query = "UPDATE `member` SET member_stamp=now(), first_name='$upd_first_name', last_name='$upd_last_name', email='$upd_email', password='$upd_password',  profile_vis_idprofile_vis='$upd_profilevis', profile_link='$upd_link', prof_image='$mypic', bio='$upd_bio' WHERE idmember='$id'"; 

    //displays the results into a table 
    $result = mysqli_query($dbc, $query) or die('Error querying database.'); 

    move_uploaded_file($temp,"images/$mypic"); 

    echo "<h2>Your profile has been updated</h2><br /><h3>Here is your profile picture</h3>"; 
    echo "<img border='1' width='200' height='200' src='images/$mypic'>"; 

    mysqli_close($dbc); 

    } 
?> 
+0

당신이 보여'('오류 데이터베이스 쿼리') 다이'와'를 (mysqli_error ($의 DBC))'대신 죽을 수 mysql 오류 메시지? – Fabricator

+0

그래서 나는 당신이 제안한 것들로 두 가지 진술을 모두 대체했습니다. 데이터베이스에 이미 데이터가있는 경우 작동하지 않고이를 보여줍니다 ... 'PRIMARY'키에 중복 항목 '2-6'이 표시되어 기존 항목을 새 업데이트로 업데이트하는 것입니다. 두 경우 모두 작동하는지 코드에 추가하는 것이 좋습니다. –

+0

코드에서 두 가지 다른 문제가 있습니다. SQL 삽입 ("... $ industries ','$ id ') ...") 및 교차 사이트 스크립팅 ('... value = "< ? php echo $ _REQUEST ... '자세한 내용 : [link] (http://en.wikipedia.org/wiki/SQL_injection) 및 [link] (http://en.wikipedia.org/wiki/Cross- site_scripting) – Tom

답변

1

당신은 트랜잭션의 모든 작업을 마무리해야 할 (I 오류를 얻을 경우).

if (isset($_POST['industries'])) { 
    $industry_ids = $_POST['industries']; 
    $id = $_POST['id']; 

    try { 
     $dbc->begin_transaction(); 
     $dbc->query("delete from industry_has_member where member_idmember=$id") or throw new Exception($dbc->error); 

     foreach ($industry_ids as $industry_id) { 
      $dbc->query("insert ignore into industry_has_member (industry_idindustry, member_idmember) values ($industry_id, $id)" or throw new Exception($dbc->error); 
     } 
     $dbc->commit(); 
    } catch (Exception $e) { 
     echo $e->getMessage(); 
     $dbc->rollback(); 
    } 
} 
을3210
+0

하시기 바랍니다 아래 마지막 게시물에서 내 의견을보고 내 생각을 알려주세요. –

+0

@EmmanuelHenri, 맞습니다. 그에 따라 답변을 업데이트했습니다 – Fabricator

+0

이 함수는 if (isset) 및 foreach() 함수 아래에 있다고 가정합니다. 덕분에 –

0

봅니다으로 삽입 질문을 확장하는

on duplicate key update 

참조 : Insert into a MySQL table or update if exists

+0

덮어 쓰지 않으려면 위의 내용을 사용하고 덮어 쓰지 않으려면 user3678068의 대답을 사용하십시오 – user3622622

+0

무엇이 있습니까? 정말 예를 들어, 업데이 트입니다. 사용자가 예를 들어 업계 2-3-4 이미 MySQL 데이터베이스에있는 경우, 그리고 사용자가 1-4-6을 선택하는 양식으로 업데이 트하면 대신 1-4-6 싶어요 이 사용자와 함께 DB에 표시하십시오. 지금 REPLACE INTO 또는 UPDATE ON DUPLICATE 문을 사용하면 DB에서이 사용자 ID로 1-2-3-4-6을 표시합니다.이 경우 다른 방식으로 접근해야합니다. 아이템을 체크 할 때와 체크하지 않을 때 다른 이름을 만들어야합니다. 그래서 나는 creat합니다. e 점검되지 않은 항목을 삭제하고 선택된 항목을 추가하는 논리. 너희들은 어떻게 생각하니? –

+0

내 코드와 논리를보고 마침내 내 논리와 코드에 대한 대답을 발견하고이를 (change.php) 업데이트하고 작동합니다! 너를 도와 줘서 고마워. 내가 알아낼 수있게 도와 줬어. –

관련 문제