2013-02-13 88 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