2013-02-13 90 views
0

我正在創建一個客戶帳戶頁面,該頁面顯示數據庫中的信息並允許客戶編輯其信息。下面的代碼顯示了當相關的db列中只有一個值時選擇的相關選項,但當列中存在多個值時因此停止預先選擇值,因此不適用於多選元素在頁面上。預先選擇匹配db值的多選選項

如何修改if($row1['notifications']=='New_Items'),以便在選擇多個值時工作?添加方括號['notifications[]']=='New_Items'將引發錯誤消息"Notice: Undefined index notifications[]"並阻止預選任何值。

多選表單元素的結構爲name =「element_name []」,並插入到數據庫中作爲數組插入到數據庫中,並在插入數組時插入數組implode。當值是牽強,我使用str_replace每個選項之後剝離的逗號,以便它可以恰當地比較值期權的價值(似乎沒有成爲一個需要引爆值)

<?php 
try { 
$stmt = $conn->prepare("SELECT * FROM customer_info WHERE user_id = :user_id"); 
$stmt->bindValue(':user_id', $user_id); 
$stmt->execute(); 
}catch(PDOException $e) {echo $e->getMessage();} 
$row = $stmt->fetch(); 
$row1 = str_replace(',', '', $row); 
?> 
<form action="account_information-exec.php" method="post"> 
    <select name="notifications[]" multiple="multiple" >    
    <option value="New_Items" <?php if($row1['notifications']=='New_Items') echo "selected='selected'"; ?>>New items</option>   
    <option value="Sale_Items" <?php if($row1['notifications']=='Sale_Items') echo "selected='selected'"; ?>>Sale items</option> 
    </select> 
<input type="submit" value="submit"> 
</form> 

account_information-exec.php - 文件,其插入和/或更新DB

<?php 
require_once "config/config.php"; // Connects to db 
$user_id = $_SESSION['SESS_USER_ID']; 
try {   
$stmt = $conn->prepare('INSERT INTO customer_info (user_id, notifications) 
VALUES(:user_id, :notifications)     
ON DUPLICATE KEY UPDATE notifications = :notifications2');  
    function bindMultiple($stmt, $params, &$variable, $type) { 
    foreach ($params as $param) { 
     $stmt->bindParam($param, $variable, $type); 
     } 
    } 
    $stmt->bindParam(':user_id', $user_id);  
    bindMultiple($stmt, array(':notifications', ':notifications2'), implode(',', $_POST['notifications']), PDO::PARAM_STR); 
    $result = $stmt->execute(); 
} catch(PDOException $e) {echo $e->getMessage();} 

回答

0

我假定$ ROW1 [ '通知']被存儲爲選定值的串接字符串。如果是的話,試試這個來代替:

if(strpos($row1['notifications'], 'New_Items') >= 0) 

請注意,您應該考慮分隔符(不知道爲什麼你剝逗號,有沒有留下空間?)。

+0

我不相信它被存儲爲一個串聯的字符串(除非內置函數在account_information-exec.php中執行該操作?)。我剝離逗號的原因是,它可以正確地將該值與該選項的值進行比較(否則它將逗號讀爲一個字符) – 2013-02-13 05:50:31