2014-09-22 2 views
0

mongoDB에서 배열을 업데이트하려고하는데 코드가 오류없이 실행되고 있지만 문서가 업데이트되지 않습니다. 내가 POST 방식으로 다른 파일에서 'ID'를 촬영하고이 파일에 필요한 문서를 검색 한mongoDB에서 PHP 업데이트 쿼리가 작동하지 않습니다.

<?php 
include 'connection.php'; 
session_start(); 
$username = $_SESSION ['username']; 
$collection = $database->selectCollection ($username); 

$books = $collection->find (array (
     '_id' => new MongoId ($_POST ['id']) 
)); 
$book = $books->getNext(); 
$imgid = $book ['imgid']; 
$id = $book['_id']; 

if (isset ($_POST ['formsubmit'])) { 

    $gridFS = $database->getGridFS(); 

    // if (isset ($_FILES ['pic'])) 
    // $imgid = $gridFS->storeUpload ('pic', array (
    // "username" => $username 
    //)); 

    $collection->update (array (
      "_id" => new mongoId ($id) 
    ), array (
      '$set' => array (
        'bookname' => $_POST ['bookname'], 
        'authname' => $_POST ['authname'], 
        'pubname' => $_POST ['pubname'], 
        'imgid' => $imgid, 
        'cost' => $_POST ['cost'] 
      ) 
    )); 

    echo '<h3>File Updated Successfully</h3>'; 

} 
$mongo->close(); 
?> 
<html> 
<head> 
<title>Online Book Exchange::Exchange old/Used books</title> 
<link rel="icon" href="images/favicon.ico"> 
<link href="style/own.css" rel="stylesheet" type="text/css"> 
</head> 
<body> 
    <div class="container_box"> 

     <div class="navbar"> 
      <p> 
       <a href="session.php">Dash Board</a> &nbsp;|&nbsp; <a 
        href="logout.php" 
        onClick="return confirm('Are you sure you want to Logout?')">Logout</a> 
      </p> 
     </div> 
     <br> <br> 
     <div class="motofont"> 
      <h3> 
       <img src="images/LogoShortMedium.png" alt="Online book store" 
        width="162" height="39" />&nbsp;&nbsp;&nbsp; Edit Book 
      </h3> 
      <hr> 
     </div> 
     <br> <br> 
     <div id="errorBox"></div> 
     <form name="form" method="POST" enctype="multipart/form-data" 
      action="editbook.php"> 
      <table width="60%" cellspacing="2" cellpadding="5" align="center"> 
       <tr> 
        <td> 
         <div class="reg_font">Book Name :</div> 
        </td> 
        <td><input type="text" name="bookname" id="bookname" class="txt" 
         value="<?php echo $book['bookname']; ?>" /></td> 
       </tr> 
       <tr> 
        <td> 
         <div class="reg_font">Author Name:</div> 
        </td> 
        <td><input type="text" name="authname" id="authname" class="txt" 
         value="<?php echo $book['authname']; ?>" /></td> 
       </tr> 
       <tr> 
        <td> 
         <div class="reg_font">Publication Name:</div> 
        </td> 
        <td><input type="text" name="pubname" id="pubname" class="txt" 
         value="<?php echo $book['pubname']; ?>" /></td> 
       </tr> 
       <tr> 
        <td> 
         <div class="reg_font">Cost</div> 
        </td> 
        <td><input type="text" name="cost" id="cost" class="txt" 
         value="<?php echo $book['cost']; ?>" /> <input type="hidden" 
         name="id" id="id" value="<?php $id?>" /></td> 
       </tr> 
       <tr> 
        <td><div class="reg_font">Upload an Image:</div></td> 
        <td><input type="file" name="pic" id="pic" class="btn_2" /></td> 
       </tr> 
       <tr> 
        <td colspan="2" align="center" valign="middle"><button 
          type="submit" value="Register" name="formsubmit" id="formsubmit" class="btn">Edit</button></td> 
       </tr> 
      </table> 
     </form> 
     <hr> 
    </div> 
</body> 
</html> 

:

여기 내 코드입니다. 그럼 난 업데이트 쿼리를 인용했다. 하지만 작동하지 않습니다

이미지가 양식에서 선택되었는지 어떻게 확인합니까? 새로운 이미지가 업로드되면 기존 이미지를 교체하고 싶습니다. 사전

답변

2

에서

덕분에 내가 POST 방식으로 다른 파일에서 'ID'를 촬영하고이 파일에 필요한 문서 을 검색했다. 그럼 난 업데이트 쿼리를 인용했다. 당신이 컬렉션에서 하나의 문서를 선택하는 경우는이

작동하지 어떤 문서가 발견되지 않은 경우, 당신은 편리 (연관 배열로) 일치하는 첫 번째 문서를 반환 MongoCollection::findOne(), 또는 null을 사용하는 것이 좋습니다. 이 방법은 커서를 find()으로 만들고 getNext()을 호출하는 것보다 효율적입니다.

한 눈에 식별자 값이 제대로 표시되지 않아 양식이 작동하지 않는다고 가정합니다. 귀하의 예를 인용하십시오 :

<input type="hidden" name="id" id="id" value="<?php $id?>" /> 

<?php $id?>은 본질적으로 NOP입니다. 아마도 $id을 문자열로 대신 인쇄하는 것이 좋습니다.

측면 관찰로 업데이트 쿼리의 imgid 필드에 $set 필드가 표시되지 않습니다. find() 쿼리와 업데이트 사이에이 값은 변경되지 않습니다. 또한 $id은 이전에 MongoId 개체 여야하는 $book['_id']에 이미 할당되어 있습니다. 이 경우 업데이트 기준에 새 MongoId 개체를 구성 할 이유가 없습니다. $id은 그대로 사용할 수 있어야합니다 (MongoId이므로).

이미지가 양식에서 선택되었는지 어떻게 확인합니까? 새로운 이미지가 업로드되면 기존 이미지를 대체하고 싶습니다.

GridFS 파일에 사용자 이름을 저장하는 것 외에도 필요하면 파일 설명서에서 관련 서적을 쉽게 확인할 수 있도록 책 식별자를 추가하는 것이 좋습니다. 주석이 달린 코드가 올바른 것으로 보입니다. 누락 된 부분은 원래 파일 인 $book['imgid'] (있는 경우)을 삭제하는 것입니다. 새로운 GridFS 삽입 및 업데이트가 성공할 때까지이 정리 단계를 연기 할 것을 제안합니다. 별도의 노트에


: 당신은 당신의 스크립트의 끝에서 MongoClient::close()를 호출 할 수 없습니다. 사실, 문서는 영구적 인 연결을 사용하는 운전자의 능력을 뛰어 넘기 때문에 강력하게 장려하고 있습니다.

또한 사용자 이름을 콜렉션 이름으로 사용하고 있으므로 MongoDB의 collection naming restrictions을 검토하여 부주의하게 잘못된 이름을 사용하지 않도록하십시오. 이것은 일반적으로 별도의 콜렉션이 아닌 데이터베이스 레벨에서 수행되는 멀티 테넌시 (multi-tenancy)의 시도처럼 보입니다. 실제로 데이터를 분리해야하는 경우가 아니라면 시작하기 위해 단일 컬렉션에 저장하는 것이 좋습니다. 각 책 문서에 사용자 이름 또는 더 나은 사용자 식별자를 저장해야합니다. 그러나 단일 모음을 사용하면 색인을 추적하는 것이 훨씬 쉬워지고 사용자 이름을 모음 이름으로 사용할 때 발생할 수있는 충돌을 피할 수 있습니다.