我正在创建一个客户帐户页面,该页面显示数据库中的信息并允许客户编辑他们的信息。下面的代码显示了当关联的 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 - 插入和/或更新数据库的文件
<?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();}