2015-08-24 74 views
2

我一直在試圖解決這個問題,但無法在我運行測試場景時正常工作。基本上,這是一個編輯窗體,所以它從數據庫中提取存儲的值。我把它保存爲「1」或「0」,1被檢查。這也是一個複選框,而不是一個數組。複選框「已檢查」值與會話和數據庫值衝突PHP

我想弄清楚如何使會話正確地存儲我的複選框的選擇,以便如果頁面上有錯誤等,它會正確顯示我的會話值,但會發生什麼是DB值通常最終會導致這種情況。

那麼我怎樣才能最初顯示數據庫值,但如果更改顯示會話值?

這是我一直在玩的東西。

if(isset($_SESSION["include_due_date"])) {      
     $include_due_date = 'checked="checked"';     
} else {    
    if((!isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 1) { 
      $include_due_date = 'checked="checked"'; 
    } elseif((isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 0) { 
      $include_due_date = 'checked="checked"'; 
    } elseif((!isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 0) { 
      $include_due_date = ''; 
    } 
} 

任何想法?

額外的方法:

<input type="checkbox" value="1" <?php echo (isset($_SESSION['include_due_date'])?' checked="checked"' : (!isset($_SESSION['include_due_date'])) && $resInvoice[0]['include_due_date'] == 1?' checked="checked"' : ''); ?> name="include_due_date" id="include_due_date" /> 
+0

檢查框,直到您提交表單並重新加載頁面不會改變在會話中值。在第一次加載時,db值始終優先。 JS解決方案可能適合您的問題。 – mdamia

+0

如果您沒有任何「表單輸入」,那麼數據庫值就是要顯示的數據。如果你有'從表單輸入'_then這是輸入使用!_。即如果複選框設置在$ _POST中,則將數據庫設置爲true。如果複選框_is不在$ _POST_中,則將'database value'設置爲false。 –

回答

0

因此,如何能我最初首先顯示DB值,但隨後顯示 會話值,如果改變了嗎?

session_start(); // (Be sure to use session_start) 
// If the include_due_date was set by the session 
if(isset($_SESSION["include_due_date"])) { 
    // Set the value of $checked to the value of the session variable 
    // In this way, the value of the session variable takes precedence over that in the database 
    $checked = ($_SESSION["include_due_date"] === true);     
} else {    
    // The session variable wasn't set, so use the value from the database to set both the checked value and the session variable. 
    // The next request will use the value from the session variable 
    if($resInvoice[0]["include_due_date"] == 1) { 
     $_SESSION["include_due_date"] = $checked = true; 
    } else { 
     $_SESSION["include_due_date"] = $checked = false; 
    } 
} 

HTML

<input type="checkbox" value="1" <?php if ($checked) echo 'checked="checked"; ?> name="include_due_date" id="include_due_date" /> 
+0

嗯,我已經可以拉出db值並顯示了。我的問題是,我需要它正確顯示與會話的複選框,但是當複選框未選中並提交表單,然後返回到它由於故意的測試錯誤,它不會顯示覆選框未選中,但而是從db值中檢查。看到我也嘗試過的另一種方法。 – JonnyPlow

+0

我們缺少代碼來存儲數據庫並更新會話。錯誤可以在那裏嗎?你應該顯示它。 – AndreaBogazzi