预先选择与db值匹配的Multiselect选项

时间:2013-02-13 05:24:26

标签: php multi-select selected

我正在创建一个客户帐户页面,该页面显示数据库中的信息,并允许客户编辑他们的信息。下面的代码显示了当关联的数据库列中只有一个值时所选的相关选项,但当列中有多个值时它停止预选值,因此不适用于多选元素在页面上。

如何修改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 - 插入和/或更新数据库的文件

<?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();}

1 个答案:

答案 0 :(得分:0)

我假设$ row1 ['notifications']存储为选定值的串联字符串。如果是这样,请尝试这样做:

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

请注意,您应该考虑分隔符(不确定为什么要剥离逗号,还剩下空格吗?)。

相关问题