2016-07-23 63 views
0

我正嘗試將圖像上傳到現有文檔(通過添加一個字段)。我正在通過電子郵件輸入查找我的文檔。 這裏是我的代碼: -如何添加一個字段到MongoDB文檔使用PHP?

<?php 

$errors = array(); 
$data = array(); 
$_POST = json_decode(file_get_contents('php://input'), true); 

$name=$__POST["mn"]; 
$email=$__POST["me"]; 
$i2u=$_POST["image2upload"]; 

$binary = base64_decode($i2u); 
$filepath = 'images/newuploads/'.$name.'/'.$name.'.jpg'; 
$imgurl = 'http://localhost/portfolio3/php/'.$filepath; 
file_put_contents($filepath, $binary); 

$m = new MongoClient(); 
$db = $m->mydb2->mycol2; 
$foundRecord = $db->find(array('Email'=>$email));  

$foundRecord->update(array(‘$set’ => array(‘uploadpic1’ => new MongoBinData(file_get_contents($imgurl))))); 

?> 

如何使用PHP多一個字段添加到MongoDB的文件?

回答

0

首先,如果你正在尋找一個記錄,你應該使用$db->findOne

然後,您可以執行以下操作:

$foundRecord = $db->findOne(array('Email'=>$email)); 
$foundRecord['uploadpic1'] = new MongoBinData(file_get_contents($imgurl); 
$db->save($foundRecord); 

因爲你使用findOne它會保存到提取的記錄,而不是使用時創建新記錄$db->save($foundRecord);

否則,如果您要使用update您需要指定其中的查詢:

$db->update(array('Email'=>$email), array('$set' => array('uploadpic1' => new MongoBinData(file_get_contents($imgurl))))); 
+0

謝謝。有用。! –

相關問題