2013-09-29 27 views
0

美好的一天!PHP:如何處理上傳2個文件和輸出

,我會說我剛開始學習PHP的,所以把它容易對我做起......

基本上,我有一個表單,允許用戶上傳4張圖片(與完成其他字段一起) 。提交時,表單調用一個PHP文件(下面的代碼),它基本上將細節添加到數據庫並將圖像上傳到文件服務器。這對我正在努力完成的工作很好。我遇到麻煩的地方是確認信息。

由於我有2個獨立的上傳領域,我基本上有2如果語句,確認兩個文件已被正確上傳。我想簡化這一點,所以我只需要顯示1條確認消息。

有關如何簡化此操作的任何想法?我在考慮如果兩個文件都成功上傳,代碼將會顯示,如果是這樣的話echo「x」,否則echo「y」。我對move_uploaded_file函數不太熟悉,所以我不確定是否可以在那裏使用用戶語句...任何想法都將非常感激。

//This is the directory where images will be saved 
$target = "path/"; 
$target = $target . basename($_FILES[controlcreative][name]); 
$target2 = "path/"; 
$target2 = $target2 . basename($_FILES[winnercreative][name]); 

$pic=($_FILES['controlcreative']['name']); 
$pic2=($_FILES['winnercreative']['name']); 

$con=mysqli_connect(); 
// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$sql="INSERT INTO experiments (vertical, pagetype, pagename, primarykpitype, primarykpilift, primarysignificant, testobjective, takeawayone, optimizationtype, controlcreative, winnercreative) 
VALUES 
('$_POST[vertical]','$_POST[pagetype]','$_POST[pagename]','$_POST[primarykpitype]','$_POST[primarykpilift]','$_POST[primarysignificant]','$_POST[testobjective]','$_POST[takeawayone]','$_POST[optimizationtype]','$pic','$pic2')"; 

if (!mysqli_query($con,$sql)) 
    { 
    die('Error: ' . mysqli_error($con)); 
    } 
echo "1 record added"; 


//Writes the photo to the server 
if(move_uploaded_file($_FILES[controlcreative][tmp_name], $target)) 
{ 

//Tells you if its all ok 
echo "The file ". basename($_FILES[controlcreative][name]). " has been uploaded, and your information has been added to the directory"; 
} 
else { 

//Gives and error if its not 
echo "Sorry, there was a problem uploading your file."; 
} 

//Writes the photo to the server 
if(move_uploaded_file($_FILES[winnercreative][tmp_name], $target2)) 
{ 

//Tells you if its all ok 
echo "The file ". basename($_FILES[winnercreative][name]). " has been uploaded, and your information has been added to the directory"; 
} 
else { 

//Gives and error if its not 
echo "Sorry, there was a problem uploading your file."; 
} 


mysqli_close($con); 

回答

0

我通過$_FILES就不斷循環,這可能會爲您節省一些代碼,並設置一個錯誤標誌

$error = false; 
foreach($_FILES as $name => $file) 
{ 
    $target = '/path/to/destination/' . $file['name']; 
    if(!move_uploaded_file($file['tmp_name'], $target)) $error = true; 
} 

然後

if(!$error) echo 'All files uploaded'; 
+0

我的實際工作問題的答案...感謝儘管協助。 if((move_uploaded_file($ _ FILES [controlcreative] [tmp_name],$ target))&& move_uploaded_file($ _ FILES [winnercreative] [tmp_name],$ target2))' – user2828701