PHP 表单必须提交两次才能更新复选框


PHP Form must be submitted twice to update checkbox

我对PHP还是比较陌生的。我正在尝试为会员构建一个隐私设置页面,以选择退出触发事件的自动电子邮件(即私人消息通知)。我希望根据数据库设置自动设置复选框。截至目前,表单确实正确更新了数据库,但复选框状态不会显示正确的设置,除非按两次"提交"按钮或重新加载页面。设置为"0"表示未选中,"1"表示选中。我很想使用Ajax或jQuery来处理这个问题,但我根本不知道这些。

隐私设置.php

<?php
  $id = "";
  $pm_mail_able = "";
  $pm_email = "";
  if (isset($_GET['id'])) {
    $id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
  } else if (isset($_SESSION['idx'])) {
    $id = $logOptions_id;
  } else {
    header("location: index.php");
    exit();
  }
  //query to get checkbox status
  $sql = mysql_query("SELECT * FROM members WHERE id='$id'");
  while($row = mysql_fetch_array($sql)){
    $pm_mail_able = $row['pm_mail_able'];
  }
  switch ($pm_mail_able) {
    case 0:
      $pm_setting = NULL;
      break;
    case 1:
      $pm_setting = "checked='"checked'"";
      break;
  }
  if(isset($_GET['pm_email']) && !empty($_GET['pm_email'])) {
    $updateqry = mysql_query("UPDATE members SET pm_mail_able='1' WHERE id='$id'");
  } else {
    $updateqry = mysql_query("UPDATE members SET pm_mail_able='0' WHERE id='$id'");
  }
?>
<html>
    Email Notifications<br />
    <form name="testform" method="get" action="PvResult.php">
        When a friend sends me a private message
        <input type="checkbox" name="pm_email" value="on"<?php echo $pm_setting;?> />
        <br /><br />
        <input type="submit" value="Submit" />
    </form>
</html>

光伏结果.php

<?php
  $url = 'http://www.mywebsite.com';
  //If the form isn't submitted, redirect to the form
  if(!isset($_GET['Submit']))
    header('Location: '.$url.'/privacysettings.php');
  //Redirect to the correct location based on form input
  $pm_email = $_GET['pm_email'];
  $url .= '/privacysettings.php?pm_email='.$pm_email;
  header('Location: '.$url);
?>

好的,希望这不会回答您的问题,而是为您提供一些您可能需要考虑的最佳实践。

您可以相对轻松地将这两个脚本合并为一个。 另外,我强烈建议使用 POST 而不是 GET;GET非常有限,不打算像您正在使用它那样提交数据。 如果您要更改后端存储中的数据,使用GET会咬您。 也许不是今天,也许不是明天,但它会的,相信我。

确实应该考虑迁移到PDO而不是mysql_功能。PDO在处理参数化查询方面要好得多,为了更好的安全性,你真的应该在这里拥有它,如果有一天你想移动到不同的数据库系统,它更便携。

我仍然有点模糊您的应用程序如何获得$id。 大多数应用从 $_SESSION 变量获取它,确保用户已成功验证登录名。 如果你不这样做,这样做。 您可能想彻底消化本文,它有很多关于身份验证和"记住我"类型功能的多汁最佳实践。

这里有一点重写。 我还没有真正测试过它,但它应该让你对你的即时需求有一个很好的主意。 如果它抛出任何错误(记住免责声明:我还没有真正测试过它!),让我知道,我会尝试调试它。

<?php
$message = '';
$pm_setting = '';
$id = 0;
// Put your $id retrieval logic here.  It should look something like:
if (isset($_SESSION['id'])) {
    $id = $_SESSION['id'];
    if (!preg_match('/^''d{1,10}$/', $id) > 0) {
        // Someone is trying to hack your site.
        header("location: scum.php");
        exit();
    }
    $id = intval($id);
}
// Quick security note: You might want to read up on a topic called
// session hijacking if you want to ensure your site is secure and
// this $id isn't spoofed.
if (isset($_POST['Submit'])) {
    // The form is being submitted.  We don't need to read the current
    // pm_mail_able setting from the database because we're going to
    // overwrite it anyway.
    if ($id > 0) {
        $pm_mail_able = 0;
        if (isset($_POST['pm_email']) && $_POST['pm_email'] === 'on') {
            $pm_mail_able = 1;
            $pm_setting = 'checked ';
        }
        $query = 'UPDATE members SET pm_mail_able='.$pm_mail_able.
            ' WHERE id = '.$id;
        mysql_query($query);
        // Another quick security note: You REALLY need to consider
        // updating to PDO so that you can bind these parameters
        // instead. The mysql_ functions are probably going to be
        // deprecated soon anyway.
        if (mysql_affected_rows($query) > 0)
            $message = '<p style="color: #00a000;">Settings saved!</p>';
        else
            $message = '<p style="color: #a00000;">User id not valid.</p>';
    }
    else
        $message = '<p style="color: #a00000;">User id not valid.</p>';
}
else {
    // This is the first load of the form, we need to just display it
    // with the existing setting.
    if ($id > 0) {
        $query = mysql_query('SELECT * FROM members WHERE id = '.$id);
        if (($row = mysql_fetch_array($query, MYSQL_ASSOC)) !== FALSE)
            if ($row['pm_mail_able'] === 1) $pm_setting = 'checked ';
    }
}
?>
<html>
    <body>
        <?= $message ?>
        <!-- Without action parameter, form submitted to this script. -->
        <form name="testform" method="post">
            E-mail notifications<br />
            <input type="checkbox" name="pm_email" value="on" <?= $pm_setting ?>/>
            When a friend sends me a private message
            <br /><br />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

尝试执行这些设置,看看它是否有效:

1)您需要在"on"和"checked=checked"之间添加一个空格

<input type="checkbox" name="pm_email" value="on" <?php echo $pm_setting;?> />

2)您必须通过其名称而不是其值来引用提交按钮

<input type="submit" name="Submit" value="Send" />

3)当设置为"0"时,$pm_setting设置为空字符串,而不是NULL

case 0:
    $pm_setting = '';

4)也许$_GET['pm_email']存在一些问题,并且else总是在执行

5)如果当您按两次提交按钮时事情有效,则意味着表单正在传递一些使代码工作的GET变量,因此请尝试发现这是什么var