0
我有3行,每行都有一个复选框,当我取消选中所有复选框并单击保存时我在我的else语句中收到错误。如果我一次取消选中框并单击保存,当我到达最后一个复选框并单击保存时,我也会在else语句中收到错误。使用PHP PDO更新复选框的数据库值不更新所有复选框
这是我的问题 - 我如何让所有的复选框没有收到错误没有选中?
这是我的PHP代码:
//Update Social Preferences with new value for display on homepage
$settingsArray = array('myfacebook', 'mytwitter', 'mygoogle');
if(isset($_POST['btn-save']))
{
if(isset($_POST['mysocial']))
{
$values = array();
foreach($_POST['mysocial'] as $selection)
{ if(in_array($selection, $settingsArray))
{ $values[ $selection ] = 1; }
else
{ $values[ $selection ] = 0; }
} // end of foreach.
$user_id = $_SESSION['user']['id'];
try // save user selection to the database
{
$stmt = $db->prepare("UPDATE social_preferences SET my_facebook = :myfacebook, my_twitter = :mytwitter, my_google = :mygoogle WHERE user_id = :userID");
$stmt->bindParam(":userID", $userid, PDO::PARAM_INT);
$stmt->bindParam(':myfacebook', $values['myfacebook']);
$stmt->bindParam(':mytwitter', $values['mytwitter']);
$stmt->bindParam(':mygoogle', $values['mygoogle']);
$stmt->execute();
header("Location: admin-social-test.php");
die("Redirecting to admin-social-test.php");
} catch(PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
}
else
{ $noCheckbox = 'No checkbox selection made...'; }
} // End of, if statement from the button check
这是我的HTML代码:
<input type="checkbox" name="mysocial[]" value="myfacebook" <?php echo ($result['my_facebook']==1 ? 'checked' : '');?> />
<input type="checkbox" name="mysocial[]" value="mytwitter" <?php echo ($result['my_twitter']==1 ? 'checked' : '');?> />
<input type="checkbox" name="mysocial[]" value="mygoogle" <?php echo ($result['my_google']==1 ? 'checked' : '');?> />
你真正的问题是什么? – Mike 2014-10-02 15:34:45
未选中的复选框不会在POST中发送。换句话说,除非你专门做了一些事情来解决这个问题,否则你永远不会在POST数组中看到未经检查的复选框。 – 2014-10-02 15:38:48
[如何复选框状态不总是传递给PHP脚本?](http://stackoverflow.com/questions/2520952/how-come-checkbox-state-is-not-always-passed-along- to-php-script) – 2014-10-02 15:39:54