0

I have the code below which loops through selected checkboxes and executes and sql statement.

if (isset($_POST['delete']))
{
   for($i=0;$i<$recordcount;$i++)                       
   {                        
       $deleteid = isset($_POST['checkbox'][$i]);
       echo "ID = ".$deleteid."<br />"; //Error checking
       $sqldelete = "DELETE FROM customer WHERE cus_ID = ".$deleteid."";
       echo $sqldelete."<br />"; //Error checking
       $deleters = $conn->Execute($sqldelete);                  
   }
}

This runs the sql query but it tries it run it once more than required, i.e I check two check boxes, the sql runs 3times. So this casues an error as the ID is empty. I also get an undefined offset 1.

Any advice? Thanks.

4
  • $recordcount is the amount of rows returned from SQL select statement. Commented Dec 8, 2010 at 12:11
  • 2
    isset() will return a boolean true or false in $deleteid, is that really what you want? Commented Dec 8, 2010 at 12:11
  • I want to check if the button 'delete' is pressed, the code works but the sql statements tries to execute one more than required. Commented Dec 8, 2010 at 12:12
  • The code doesn't work correctly: it will always try to delete cus_IDs 0 and 1, because the $deleteid boolean will be cast to 0 or 1 from false or true Commented Dec 8, 2010 at 12:15

3 Answers 3

3

This line is definitely wrong:

$deleteid = isset($_POST['checkbox'][$i]);

Maybe you meant it like this?

$deleteid = isset($_POST['checkbox'][$i]) 
    ? intval($_POST['checkbox'][$i]) : false;
if ($deleteid === false) {
    continue;
}

// rest of the code follows

Also, you could probably get rid of $recordcount and do a foreach over $_POST['checkbox'].

Sign up to request clarification or add additional context in comments.

Comments

2
if (isset($_POST['delete']))
{
   for($i=0;$i<$recordcount;$i++)                       
   {                        
       $deleteid = isset($_POST['checkbox'][$i]);
       if ($deleteid) {
          $sqldelete = "DELETE FROM customer WHERE cus_ID = ".$_POST['checkbox'][$i];
          echo $sqldelete."<br />"; //Error checking
          $deleters = $conn->Execute($sqldelete);                  
       }
   }
}

And escape your input for safety

Comments

0

try this

if(isset($_POST['delete']))
    {
       $i=0;
        foreach($_POST['checkbox'] as $user)
        {
            $sqldelete = "DELETE FROM customer WHERE cus_ID = ".$user."";
           echo $sqldelete."<br />"; //Error checking
         $deleters = $conn->Execute($sqldelete); 
            $i++;
        }

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.