2014-02-19 54 views
0

我試圖製作一個PHP表格,只允許用戶更新MySQL表格列photo,如果photo列爲空白。目前,即使有「空白」數據以外的數據,表格仍然會更新photo列。例如,photo列包含數據「columbia.jpg」,用戶在第一個輸入中提交帶有圖像「Jefferson.jpg」的表單。 image列的數據從columbia.jpg被替換爲jefferson.jpg,而根本不應該替換它。相反,它應該返回一條錯誤消息,指出用戶在添加新圖像之前必須先刪除舊圖像。列數據只應在列數據等於「空白」時才被替換。 (不是單詞 「空白」,但 「」)。即使當SQL表列不是空白時,PHP表格也更新SQL表格

這是我的完整的PHP頁面代碼:

<?php 
if (isset($_GET["id"])) { 
    $sn = (int)($_GET["id"]); 
?> 
<!DOCTYPE html> 
<head> 
    <title>MySQL file upload example</title> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
</head> 
<body> 
    <form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data"> 
     Photo 1: <input type="file" name="photo"><br> 
     <input name="add_image" id="add_image" type="submit" value="Upload file"> 
    </form> 
    <p> 
     <a href="pdfget.php">See all files</a> 
    </p> 
</body> 
</html> 

<?php 
if(isset($_POST['add_image'])) 
{ 
$dbLink = new mysqli('daom', 'sm', 'aer', 'kabm'); 

//This is the directory where images will be saved 
$target = "images/"; 
$target = $target . basename($_FILES['photo']['name']); 
$pic=($_FILES['photo']['name']); 

$query = "SELECT photo FROM used_trailers WHERE id = $sn"; 
$result = mysqli_query($dbLink, $query); 
$array=mysqli_fetch_assoc($result); 

if($query = " "){ 
//Writes the information to the database 
     $query1 = 
      "UPDATE used_trailers ". 
     "SET photo = '$pic' ". 
     "WHERE id = $sn" ; 
     // Execute the query 
     $results = $dbLink->query($query1); 

     // Check if it was successfull 
     if($results) { 
      echo 'Success! Your file was successfully added!'; 
     } 
     else { 
      echo 'Error! Failed to insert the file' 
       . "<pre>{$dbLink->error}</pre>"; 
     } 

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

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

//Gives and error if its not 
echo "Sorry, there was a problem uploading your image."; 
} 
} else { 
echo '<p>You must first delete the "Photo 1" image, $array, in order to add a new photo. This is to prevent the server from overloading with too many images.</p>'; 
} 
} 
} 
       echo "$query1"; 
?> 

感謝您的任何幫助。所有的幫助表示讚賞。

+2

旁註:你確定你有你的支具正確完成?也就是說:'if(isset($ _ GET [「id」])){sn =(int)($ _ GET [「id」]);'它會在代碼結束時關閉,進出PHP。 –

+0

無論支撐如何,代碼的功能都與目的一致。 – Kelsey

+0

好的。我認爲這可能與它有關。很高興你在下面找到你的解決方案。 –

回答

1

腳本中存在一些錯誤。首先if ($query = " ")將始終返回true,因爲您正在分配變量$query字符串" "。要正確檢查這個,你需要使用if ($query == " ")

但是,這不會解決您的問題,因爲$query是查詢 - 不是結果。這應該工作

$query = "SELECT photo FROM used_trailers WHERE id = $sn"; 
$result = mysqli_query($dbLink, $query); 
$array = mysqli_fetch_assoc($result); 

if (empty($array['photo'])){ 
    //etc. 
} 
+0

嗯,這解決了我的問題。謝謝! – Kelsey