Php Checkbox - 进行选中和取消选中

2024-02-01

我尝试解决一个问题。

这是我的代码。

<?php

require 'connectDB.php';
print<<<_A_
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
_A_;
$mysql = new mysql();
$mysql->connect();

$dbResult = mysql_query("select * from profiles");






echo "<form action='#' method='post'>";

$dbResult = mysql_query("select * from profiles");


while ($info = mysql_fetch_array($dbResult)) {

    if ($info['isPremium'] == 0)
        echo "<input type=checkbox name='check2[]' id='check2' value=".$info['id'].">";
    else
        echo "<input type=checkbox name='check1[]' id='check1' value=".$info['id']." checked>";

    echo $info['profileName'] . "<br />";
}

echo "<p><input type='submit' name='btnPremium' /></p>";
echo "</form>";

如果用户单击一个复选框,我会向数据库发送一个查询,以使其成为 1。但是,当用户取消选中一个复选框时,我会收到此错误:未定义索引:第 43 行 C:\xampp\htdocs\googleAnalytics\GAPI\choosePremium.php 中的 check2我尝试在 arrPremium2 中取消选中:S

if (isset($_POST['btnPremium'])) {

    $arrPremium = $_POST['check1'];
    foreach($arrPremium as $result)
    {
        mysql_query("UPDATE profiles set isPremium=1 where id=".$result."");
    }

    $arrPremium2 = $_POST['check2'];
    print_r($arrPremium2);
}
?>

您的错误看起来来自:

$arrPremium2 = $_POST['check2'];

因为如果没有名为“check2”的“checked”复选框,则那里不会有 $_POST 元素(因此未定义索引)。通过执行以下操作来检查它是否存在:

if(isset($_POST['check2'])) {
    $arrPremium2 = $_POST['check2'];
    // do something
} else {
    // no check2's, do something else
}

一些你应该改掉的坏习惯:

e.g. checked="checked"是将复选框标记为已选中的正确方法。

你真的应该:

 ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php

instead.

$arrPremium = $_POST['check1'];
    foreach($arrPremium as $result)
    {
        mysql_query("UPDATE profiles set isPremium=1 where id=".$result."");
    }

不要这样做,你会让自己容易受到 MySQL 注入的影响。在使用 $result 更新数据库之前转义它,或者使用准备好的语句。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Php Checkbox - 进行选中和取消选中 的相关文章