0

I have the following code to update sql database depending on checked values. The problem is that I only want to update the values that are checked and leave the other values as is, whereas my current code updates everything as either a zero or one. I have tried many different ways to accomplish this without success. Would also welcome a suggestion as to how to make the 'else' statement concerning empty inpput only appear after Submit is clicked instead of all the time. Very new to writing code, so apologies if the answer is obvious and I am missing it, and thanks for your help!

$host="localhost";
$username="######";
$password="#######";
$db_name="signuplist";
$tbl_name="signupbydate";
$myusername=$_SESSION['logname'];
?>
    <head>
        <title>Request Date</title>
    </head>
    <body>
    <div style='margin-left:6.0in; margin-top:0.75in'>
    <p style='font-weight:bold'>
        When would you like to play golf?</p>
    <p>Choose the dates you wish to play</p>
    <p>Make sure you click 'Update' when you are done</p>
           <form name="requesttime" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
           <input type="checkbox" name="playdate[]" value="playdate1"> September 3, 2014 <br>
           <input type="checkbox" name="playdate[]" value="playdate2"> September 6, 2014 <br>
           <input type="checkbox" name="playdate[]" value="playdate3"> September 10, 2014 <br>
           <input type="checkbox" name="playdate[]" value="playdate4"> September 13, 2014 <br>
           <input type="checkbox" name="playdate[]" value="playdate5"> September 17, 2014 <br>
           <br>
           <input type="submit" value="Update" name="submit">
<?php

$cxn=mysqli_connect($host,$username,$password,$db_name)
     or die ("Couldn't Connect to Server");
$chkbox = array('playdate1', 'playdate2', 'playdate3', 'playdate4', 'playdate5');

     if(isset($_POST['submit']))
     {   $playdate = $_POST['playdate'];
         $values = array();
           foreach($chkbox as $selection )
           {     if(in_array($selection, $playdate))
                   { $values [$selection] = 1;  }
                 else
                   {$values [$selection] = 0; } 

           }
      $sql1="UPDATE $tbl_name 
             SET playdate1=$values[playdate1], playdate2=$values[playdate2], playdate3=$values[playdate3], playdate4=$values[playdate4], playdate5=$values[playdate5]
             WHERE username='$myusername'";

      mysqli_query($cxn, $sql1) or die('<br/>Error reading database: '.mysqli_error($cxn));
      mysqli_close($cxn);
    }  

    if(empty($_POST['submit'])) { echo "Make a selection";  exit; }

?>
7
  • are you saying fields can only be set to 1 but never to 0? Commented Jul 29, 2014 at 0:27
  • No, I want to retain the value that is already in the database. If the value in the database has been previously checked and is set at 1, I want to keep it that way. Thanks Commented Jul 29, 2014 at 0:29
  • doesn't "retain the checked value" mean "don't turn a 1 into a 0"? Commented Jul 29, 2014 at 0:32
  • Say I had a user check September 3 and 10 on the form last week, and now they want to add themselves for September 6, so they go to the form and check September 6. September 3 and 10 have a value of 1 that was set previously which I need to maintain, and just update September 6 to a 1. Right now it would kick the previously checked values back to zero Commented Jul 29, 2014 at 0:36
  • 1
    what if your user want to uncheck something? I think it's better to default the previous checked values checked on subsequent visits. Commented Jul 29, 2014 at 0:38

2 Answers 2

1

You can build the form that reflect the user's current setting, so the user can both check and uncheck values:

<form name="requesttime" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

<?php
$query = "select * from $tbl_name where username = ?";
$st = $cnx->prepare($query);
$st->bind_param('s', $myusername);
$st->execute();
$rs = $st->get_result();
$row = $rs->fetch_assoc();
$chkbox = array(
    'playdate1' => 'September 3, 2014', 
    'playdate2' => 'September 6, 2014', 
    'playdate3' => 'September 10, 2014',
    'playdate4' => 'September 13, 2014',
    'playdate5' => 'September 17, 2014'
);
foreach ($chkbox as $selection => $day) {
    $checked = isset($row[$selection]) && $row[$selection];
    if ($checked) {
        echo '<input type="checkbox" name="playdate[]" value="'.$selection.'" checked> '.$day.' <br>';
    } else {
        echo '<input type="checkbox" name="playdate[]" value="'.$selection.'"> '.$day.' <br>';
    }
}
?>

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

<?
if(isset($_POST['submit'])) {
     $playdate = $_POST['playdate'];
     $values = array();
       foreach($chkbox as $selection => $day)
       {     if(in_array($selection, $playdate))
               { $values[$selection] = 1; }
             else
               { $values[$selection] = 0; } 
       }
  $sql1="UPDATE $tbl_name 
         SET playdate1={$values['playdate1']}, 
             playdate2={$values['playdate2']}, 
             playdate3={$values['playdate3']},
             playdate4={$values['playdate4']},
             playdate5={$values['playdate5']}
         WHERE username='$myusername'";

  mysqli_query($cxn, $sql1) or die('<br/>Error reading database: '.mysqli_error($cxn));
  mysqli_close($cxn);
}  

if(empty($_POST['submit'])) { echo "Make a selection";  exit; }
Sign up to request clarification or add additional context in comments.

7 Comments

I get this error: Fatal error: Call to undefined method mysqli_stmt::fetch_result()
@user3830570, sorry it should have been get_result()
Thanks, looks promising, but unable to update database so far, and when I check a box and hit submit, it reverts back to its original state (either checked or unchecked). Will keep working on it!
@user3830570, this code does not contain the update part, you just need to use your original code that updates everything
Thanks-when I include original code, I get SQL syntax error at the UPDATE line, indicating 'playdate1' through 'playdate 5' as undefined index...any thoughts on how to correct that?
|
1
  //This handles the page when the request_method is GET, PUT, DELETE etc.
  if($_SERVER['REQUEST_METHOD'] == 'POST') {   
    //move the exit up so you're not adding in extra logic
    if(empty($_POST['playdate'])) { echo "Make a selection";  exit; }

    $playdate = $_POST['playdate'];

    $chkbox = array('playdate1', 'playdate2', 'playdate3', 'playdate4', 'playdate5');

    $setString = array();
     foreach($chkbox as $selection ) {     
      if(in_array($selection, $playdate)) {
        //we only grab values we want and shove them into a happy array
        $setString[] = $selection . '= 1';   
      } else {
        $setString[] = $selection . '= 0';
      } 
     }
    //if count is 0 this will act as a boolean false
    if(count($setString)) {

      //implode the array to create the correct formatting for the sql query
      $sql1=" UPDATE $tbl_name SET " . implode(',' , $setString) . " WHERE username='$myusername'";   

      //no sense in opening a connection and closing it unless we actually have data we wish to write
      $cxn=mysqli_connect($host,$username,$password,$db_name) or die ("Couldn't Connect to Server");

      mysqli_query($cxn, $sql1) or die('<br/>Error reading database: '.mysqli_error($cxn));

      mysqli_close($cxn);
    }
  }

5 Comments

That is great for keeping existing values, thanks. It still echoes 'Make a Selection' before Submit is presses, any thoughts on that, and also how to uncheck a value that is already checked. Much appreciated.
Do you mean visually uncheck a value on the page, or actually pass 0 t the database? Added a REQUEST_METHOD wrapper to it to handle non $_POST submitted pages.
Any idea how to pass the zero back to the db when a value is clicked again?
This is exactly the functionality you had before, but it's in there now.
Thanks for your help! Basically what I need is to change only a checked value. If it is currently zero, it changes to 1, and if it is currently 1, it changes to zero. Anything unchecked remains the same. Any thoughts on that, as what I have does not accomplish that yet and it is taxing my minimal and newfound knowledge...!

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.