我有一个PHP变量$ admin,对应一个复选框。当提交表单并勾选复选框时,将传递该值(设置为1)并且一切正常,但如果未勾选该变量,则会导致未定义的索引错误:
注意:未定义的索引:C:... \ admin.php
中的admin这是查询db:
的表单的php部分 if($row == 1)
{
echo '<div id="errormsg">This username is already taken</div>';
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Can't insert data");
echo '<div id="create-success">Successfully added user!</div>';
}
HTML表单:
<form action="admin.php" method="post" onSubmit="return validate(this)">
<fieldset>
<label class="reg">Username *</label> <input type="text" name="user" /><br />
<label class="reg">Password *</label> <input type="password" name="pass" /><br />
<label class="reg">Repeat Password *</label> <input type="password" name="rpass" /><br />
<label class="reg">First name:</label> <input type="text" name="fname" /><br />
<label class="reg">Last name:</label> <input type="text" name="lname" /><br />
<label class="reg">Admin?:</label> <input type="checkbox" value="1" name="admin" /><br/>
</fieldset>
<input type="submit" name="submit" value="Create User" />
</form>
哈有任何想法为什么不选中该框会导致$ admin变量特有的错误?
答案 0 :(得分:4)
如果选中复选框,它们实际上只会传递给脚本。
所以你需要检查你的PHP代码是否存在,如下所示:
if ( $_POST && isset( $_POST['admin'] ) {
$admin = $_POST['admin'];
} else {
$admin = 0;
}
编辑:
在你的脚本中我会这样做
if($row == 1) {
echo '<div id="errormsg">This username is already taken</div>';
} else {
$admin = ( $_POST && isset( $_POST['admin'] ) ? $_POST['admin'] : 0;
$add = mysqli_query($dbcon, "INSERT INTO users
(id, firstname, lastname, username, password, admin)
VALUES(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Can't insert data");
echo '<div id="create-success">Successfully added user!</div>';
}
答案 1 :(得分:1)
首先,您必须检查Post Array中的admin变量。请检查代码。
<?php
if($row == 1)
{
echo '<div id="errormsg">This username is already taken</div>';
}
else
{
// check is exist in post array
$isAdminCheck = (isset($_POST['admin']) && $_POST['admin'] == 1 )? $_POST['admin']:0;
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES (null, '$fname', '$lname', '$user', '$pass', '$isAdminCheck') ") or die ("Can't insert data");
echo '<div id="create-success">Successfully added user!</div>';
}
?>