Rameez Shah Rameez Shah - 2 years ago 168
MySQL Question

Undefined Index in Checkbox

<form method="POST" action="<?php $_SERVER['PHP_SELF']; ?>">
<table border="1" cellpadding="4">

$getQuery = "SELECT id,username,admin FROM tutorial_users ORDER BY id ASC";
$getResult = mysql_query($getQuery) or die("Query not executed");
while (list($id, $userName, $admin) = mysql_fetch_row($getResult)) {
$checked = ($admin == 1) ? 'checked="checked"' : '';
<tr align="center">
<td><?php echo $id; ?></td>
<td><?php echo $userName; ?></td>
<td><?php echo "<input type='checkbox' name='admin[]' value='$id' $checked>"; ?></td>
<?php } ?>
<input type="submit" name="submit" value="Update Role">
$updated = FALSE;
if (isset($_POST['submit'])) {
$admin = $_POST['admin'];
$admin = join(",", $admin);
$admin = "(" . $admin . ")";
$defaultQuery = "UPDATE tutorial_users SET admin=0";
$defaultResult = mysql_query($defaultQuery);
$upQuery = "UPDATE tutorial_users SET admin=1 WHERE id IN $admin";
echo $upQuery;
$upResult = mysql_query($upQuery);
$updated = TRUE;

In the above code I have 2 questions:

  1. Lets say I want every check box to be unchecked and then when I press the submit, it gives me
    undefined index $admin
    , how can I fix this?

    It is working fine when I'm checking at least one box and it passes the value to the POST array.

  2. Secondly I would like to know that is this a good approach to achieve result or we can have some other way? Personally I'm feeling it bad because if I have 1000 record then it will take a lot of time to update 2 queries one by one.

Result: What I want is pretty simple that the checked box should have value = 1 where as unchecked have 0.

Answer Source

Checkboxes are not included in the POST data when the form is submitted. You need to call isset($_POST['admin']) before you try to do anything else with it.

Also, on a side note, you need to look at the non-deprecated mysqli functions or PDO. The mysql_* functions have been deprecated and will be removed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download