2011-03-10 127 views
2

我試圖提交數據到數據庫。我有一個更新表單,其上有幾個字段,將數據從數據庫中提取到字段中。提交它會更新數據庫中的數據。這兩個領域我關心的是我在形式上的兩個圖像上傳者。當我在頁面上只有一個圖像上傳器時,我一直在成功地做到這一點,但是當我添加第二個時,無法將我的頭圍繞條件語法。以下是我用於只有一個圖像上傳器的表單的代碼。它會查看提交的元素是否爲空。如果是這樣,它會運行一個更新語句並將圖像變量遺留下來。如果圖像變量不爲空,它將運行一條更新語句,並將該字段添加到語句中。PHP/mysql有條件更新查詢

if($imgProfileFull == ""){ 
$query = "update students set `nameFirst` = '$nameFirst', `nameLast` = '$nameLast', `profile` = '$profile', `priority` = '$priority', `active` = '$active', `_modifiedDate` = '$_modifiedDate' where `id` = '$id'"; 
}else{ 
if((($_FILES["image"]["type"] == "image/jpeg") 
|| ($_FILES["image"]["type"] == "image/pjpeg")) 
&& ($_FILES["image"]["size"] < 500000)) 
{ 
    if($_FILES["image"]["error"] > 0){ 
    header("location:students.php?file=error"); 
    }else{ 
    move_uploaded_file($_FILES["image"]["tmp_name"], 
    "../images/students/full/" . $imgProfileFull); 
    } 
}else{ 
    header("location:students.php?file=error"); 
} 
$query = "update students set `imgProfileFull` = '$imgProfileFull', `nameFirst` = '$nameFirst', `nameLast` = '$nameLast', `profile` = '$profile', `priority` = '$priority', `active` = '$active', `_modifiedDate` = '$_modifiedDate' where `id` = '$id'"; 
} 

我該如何編寫我的更新語句以包含其他圖像字段。該變量將是$imgProfileThumb。基本上我想更新數據庫中的兩個圖像列,如果並且只有在它們不是空的時候。這是因爲表單的構建方式,圖像字段在技術上總是空的,除非圖像實際上傳。有什麼想法嗎?謝謝!!

回答

4

您可以使用if語句動態創建查詢。

$query = "UPDATE students SET "; 

if ($imgProfileFull !== ""){ 
    $query .= "`imgProfileFull` = '$imgProfileFull', "; 
} 

if ($imgProfileThumb !== ""){ 
    $query .= "`imgProfileThumb` = '$imgProfileThumb', "; 
} 

$query .= "`nameFirst` = '$nameFirst', 
      `nameLast` = '$nameLast', 
      `profile` = '$profile', 
      `priority` = '$priority', 
      `active` = '$active', 
      `_modifiedDate` = '$_modifiedDate' 
      WHERE `id` = '$id'"; 

您也不妨使用mysql_real_escape_string您的字符串數據,如果你沒有這樣做。

+0

謝謝!我會試一試。我會碰到你一分,並添加檢查,如果它工作,當我測試它。 :) – RyanPitts 2011-03-10 06:25:08

+0

我測試了這個,它似乎工作!謝謝@Mark! – RyanPitts 2011-03-10 08:07:53