简体   繁体   中英

Updating SQL Database With Checkbox Values

Ok I know this has been answered a few times, but I just can't seem to get mine working!

I have 8 weeks in my database (set up as columns) and I display the value of these with php as follows

<form method="post" id="updating" action="<?php $_PHP_SELF ?>">

        <?php
        $count = 1;
        foreach ($results as $v) {
            while($count<9){
                $week = Week.$count;
                $checkvalue = $v -> $week;
                ?>
                Week<?echo $count;?> <input type="checkbox" id="Week<?php echo$count;?>" name="week[]" value="<?php echo $checkvalue;?>" <?php if($checkvalue==1){?>
                checked="checked"
                <?php } ?>
                />
                <?php   
                $count++; 
            }
        }
        ?>
        <input name="update" type="submit" id="update" value="Update">
    </form>

I know it's probably not as graceful as it should be, but it does output the correct HTML for me and displays the information as it's presented in the database.

<form method="post" id="updating" action="">

        Week1 <input type="checkbox" id="Week1" name="week[]" value="1"     checked="checked"
        />
    Week2 <input type="checkbox" id="Week2" name="week[]" value="0"     />
    Week3 <input type="checkbox" id="Week3" name="week[]" value="1"     checked="checked"
        />
    Week4 <input type="checkbox" id="Week4" name="week[]" value="1"     checked="checked"
        />
    Week5 <input type="checkbox" id="Week5" name="week[]" value="0"     />
    Week6 <input type="checkbox" id="Week6" name="week[]" value="1"     checked="checked"
        />
    Week7 <input type="checkbox" id="Week7" name="week[]" value="1"     checked="checked"
        />
    Week8 <input type="checkbox" id="Week8" name="week[]" value="1"     checked="checked"
        />
<input name="update" type="submit" id="update" value="Update">
</form>

The problem I'm having is when I tick or untick those checkboxes, the updated values don't appear to be captured, and hence the database isn't being updated properly. Here's where the self post request is handled.

<?php if(isset($_POST['update']))
{
    $count = 1;
    if(isset($_POST['week']) && !empty($_POST['week']))   
    foreach($_POST['week'] as $w){ echo $w; //prints 1 all the time
$week = Week.$count;
echo $week;//prints out weeks I want to update correctly (database headings)
$query = $db->getQuery(true);

// Fields to update.
$fields = array(
    $week.'=' . $db->quote( $w ));

// Conditions for which records should be updated.
$conditions = array(
    'UserID='. (int) $user_id);

$query->update($db->quoteName('tools_engage'))->set($fields)->where($conditions);

$db->setQuery($query);

try {
    $result = $db->query(); // Use $db->execute() for Joomla 3.0.
    echo ("Values saved and updated </br>");
    $count++;
} catch (Exception $e) {
    // Catch the error.
}
}
}?>

I'm doing this in Joomla, hence the weird database update syntax, but it does work and I've used them elsewhere in this program so I know they're not the problem

As I commented in the code, the array week[] just seems to contain the value 1 for everything, no matter what boxes I check or uncheck. Which then results in every value in the database being updated to 1/true which obviously isn't right.

I have a suspicion the problem lies in my HTML output for the update form, but can't seem to crack it, any help is much appreciated!

Update: Ok so going on nvuono's suggestion I have updated my form to be like this

<?php
$count = 1;
foreach ($results as $v) {
while($count<9){
    $week = Week.$count;
    $checkvalue = $v -> $week;
    ?>
    Week<?echo $count;?> <input type="checkbox" id="Week<?php echo$count;?>" name="week[<?php echo $count;?>]" value="1" <?php if($checkvalue==1){?>
    checked="checked"
    <?php } ?>
    />
<?php   
$count++; 
}
}
?>

So now each name has an index in the array does it not? If that is the case, should my

if(isset($_POST['update']))

section not now be printing out all the values in the array in the order they've been entered?

ie. My logic would be that it prints out 1,0,0,1,0,0,0 (box 1 and 4 checked) or what ever boxes are checked. But instead it just prints out 1,1 so I've no way of knowing what index they are, and subsequently what week I should be updating

I added some really hacky way of doing the update. You need to beware of SQL Injection and other bad things when using post ... make sure you always validate and sanitize your data. The "hacky" way works because we're working with integer values and those are easily cleaned.

Screenshot:

在此处输入图片说明

This is my table... I called it so for stackoverflow...

+----+-------+-------+-------+-------+-------+-------+-------+-------+
| id | week1 | week2 | week3 | week4 | week5 | week6 | week7 | week8 |
+----+-------+-------+-------+-------+-------+-------+-------+-------+
|  1 |       |       |       |       |       |       |       |       |
|  2 | 1     |       |       |       |       |       |       |       |
|  3 | 1     |       | 1     |       |       |       |       |       |
|  4 | 1     |       | 1     |       | 1     |       |       |       |
|  5 | 1     |       | 1     |       | 1     |       | 1     |       |
+----+-------+-------+-------+-------+-------+-------+-------+-------+

This is my PHP file.... (stick it in an empty PHP document to run, it's self contained besides changing the db connection and query)

<?php 
$mysqli = new mysqli("localhost", "root", "password", "test"); 

if (!empty($_POST)) {
   print "<pre>POST VARS: \n".print_r($_POST,true)."</pre>";

   foreach($_POST as $i => $data) 
   { 
      if (substr($i,0,3)=='row' && is_numeric(substr($i,3)))
      {
         $row_id = substr($i,3);  
         $data = array_flip($data); 
         $values = array(); 

         for ($x=1; $x<9; $x++) {
            $values[] = "week$x = ". ((isset($data[$x])) ? '1' : '0');  
         }   

         $stmt = "\nupdate so ".
                 "\n  set ".implode(", \n      ",$values).
                 "\n  where id = $row_id; \n"; 

         $update = $mysqli->query($stmt); 
         if ($update) { print "Row $row_id updated successfully.<br/>"; } 
      }
      print "<br/>"; 
   }
}
$result = $mysqli->query("select * from so"); 

$mysqli->close();
?>

<form method="post" id="updating" action="<?php $_PHP_SELF ?>"> 
   <?php
   while($row = $result->fetch_object())
   {

      $count = 1;

      print "<div style='border:1px solid black; display:inline-block;'>\n";
      print "Row ".$row->id."<br/>\n"; 
      while($count < 9) 
      {
         $week = "week$count";

         $checkvalue = $row->{$week};
         ?>
         Week<?php echo $count ?> <input type="checkbox" id="Week<?php echo$count;?>" name="row<?php echo $row->id 
         ?>[]" value="<?php echo $count;?>" <?php if($checkvalue==1){
         ?>  checked="checked" <?php } ?> />&nbsp;&nbsp;&nbsp;
         <?php   
         $count++; 
      }
      print "</div><br/><br/>\n\n\n"; 
   }
   ?>
        <input name="update" type="submit" id="update" value="Update">
    </form>

This is the $_POST after submit:

POST VARS: 
Array
(
    [row2] => Array
        (
            [0] => 1
        )

    [row3] => Array
        (
            [0] => 1
            [1] => 3
        )

    [row4] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 5
        )

    [row5] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 5
            [3] => 7
        )

    [update] => Update
)

My "view source" of the form:

<form method="post" id="updating" action=""> 
   <div style='border:1px solid black; display:inline-block;'>
Row 1<br/>
         Week1 <input type="checkbox" id="Week1" name="row1[]" value="1"  />&nbsp;&nbsp;&nbsp;
                  Week2 <input type="checkbox" id="Week2" name="row1[]" value="2"  />&nbsp;&nbsp;&nbsp;
                  Week3 <input type="checkbox" id="Week3" name="row1[]" value="3"  />&nbsp;&nbsp;&nbsp;
                  Week4 <input type="checkbox" id="Week4" name="row1[]" value="4"  />&nbsp;&nbsp;&nbsp;
                  Week5 <input type="checkbox" id="Week5" name="row1[]" value="5"  />&nbsp;&nbsp;&nbsp;
                  Week6 <input type="checkbox" id="Week6" name="row1[]" value="6"  />&nbsp;&nbsp;&nbsp;
                  Week7 <input type="checkbox" id="Week7" name="row1[]" value="7"  />&nbsp;&nbsp;&nbsp;
                  Week8 <input type="checkbox" id="Week8" name="row1[]" value="8"  />&nbsp;&nbsp;&nbsp;
         </div><br/><br/>


<div style='border:1px solid black; display:inline-block;'>
Row 2<br/>
         Week1 <input type="checkbox" id="Week1" name="row2[]" value="1"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week2 <input type="checkbox" id="Week2" name="row2[]" value="2"  />&nbsp;&nbsp;&nbsp;
                  Week3 <input type="checkbox" id="Week3" name="row2[]" value="3"  />&nbsp;&nbsp;&nbsp;
                  Week4 <input type="checkbox" id="Week4" name="row2[]" value="4"  />&nbsp;&nbsp;&nbsp;
                  Week5 <input type="checkbox" id="Week5" name="row2[]" value="5"  />&nbsp;&nbsp;&nbsp;
                  Week6 <input type="checkbox" id="Week6" name="row2[]" value="6"  />&nbsp;&nbsp;&nbsp;
                  Week7 <input type="checkbox" id="Week7" name="row2[]" value="7"  />&nbsp;&nbsp;&nbsp;
                  Week8 <input type="checkbox" id="Week8" name="row2[]" value="8"  />&nbsp;&nbsp;&nbsp;
         </div><br/><br/>


<div style='border:1px solid black; display:inline-block;'>
Row 3<br/>
         Week1 <input type="checkbox" id="Week1" name="row3[]" value="1"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week2 <input type="checkbox" id="Week2" name="row3[]" value="2"  />&nbsp;&nbsp;&nbsp;
                  Week3 <input type="checkbox" id="Week3" name="row3[]" value="3"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week4 <input type="checkbox" id="Week4" name="row3[]" value="4"  />&nbsp;&nbsp;&nbsp;
                  Week5 <input type="checkbox" id="Week5" name="row3[]" value="5"  />&nbsp;&nbsp;&nbsp;
                  Week6 <input type="checkbox" id="Week6" name="row3[]" value="6"  />&nbsp;&nbsp;&nbsp;
                  Week7 <input type="checkbox" id="Week7" name="row3[]" value="7"  />&nbsp;&nbsp;&nbsp;
                  Week8 <input type="checkbox" id="Week8" name="row3[]" value="8"  />&nbsp;&nbsp;&nbsp;
         </div><br/><br/>


<div style='border:1px solid black; display:inline-block;'>
Row 4<br/>
         Week1 <input type="checkbox" id="Week1" name="row4[]" value="1"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week2 <input type="checkbox" id="Week2" name="row4[]" value="2"  />&nbsp;&nbsp;&nbsp;
                  Week3 <input type="checkbox" id="Week3" name="row4[]" value="3"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week4 <input type="checkbox" id="Week4" name="row4[]" value="4"  />&nbsp;&nbsp;&nbsp;
                  Week5 <input type="checkbox" id="Week5" name="row4[]" value="5"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week6 <input type="checkbox" id="Week6" name="row4[]" value="6"  />&nbsp;&nbsp;&nbsp;
                  Week7 <input type="checkbox" id="Week7" name="row4[]" value="7"  />&nbsp;&nbsp;&nbsp;
                  Week8 <input type="checkbox" id="Week8" name="row4[]" value="8"  />&nbsp;&nbsp;&nbsp;
         </div><br/><br/>


<div style='border:1px solid black; display:inline-block;'>
Row 5<br/>
         Week1 <input type="checkbox" id="Week1" name="row5[]" value="1"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week2 <input type="checkbox" id="Week2" name="row5[]" value="2"  />&nbsp;&nbsp;&nbsp;
                  Week3 <input type="checkbox" id="Week3" name="row5[]" value="3"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week4 <input type="checkbox" id="Week4" name="row5[]" value="4"  />&nbsp;&nbsp;&nbsp;
                  Week5 <input type="checkbox" id="Week5" name="row5[]" value="5"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week6 <input type="checkbox" id="Week6" name="row5[]" value="6"  />&nbsp;&nbsp;&nbsp;
                  Week7 <input type="checkbox" id="Week7" name="row5[]" value="7"   checked="checked"  />&nbsp;&nbsp;&nbsp;
                  Week8 <input type="checkbox" id="Week8" name="row5[]" value="8"  />&nbsp;&nbsp;&nbsp;
         </div><br/><br/>


        <input name="update" type="submit" id="update" value="Update">
    </form>

edit
I came back to this answer to reference something and I just realized I was re-using ID values for the checkboxes. It wasn't a problem in this situation but it is always bad practice. Each checkbox should have an ID that is unique on the page. So.... it should really be id="row1week1" , id="row1week2" ... id="row8week1" ... id="row8week8" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM