PHP - How to update data to MySQL when click a radio button

29,522

Solution 1

Something to set you off on a prettier path:

  // $_POST is way cooler than $_REQUEST
  if (isset($_POST['gender']) && !empty($_POST['gender'])) {

      // sql injection sucks
      $gender = my_real_escape_string($_POST['gender']);

      // cast it as an integer, sql inject impossible
      $id = intval($_GET['id']);

      if($id) {
          // spit out the boolean INSERT result for use by client side JS
          if(mysql_query("UPDATE users SET gender=$gender WHERE id=$id")) {
              echo '1';
              exit;
          } else {
              echo '0';
              exit;
          }
      }
  }

Assuming the same markup, an ajaxy solution (using jQuery):

<script>
var id = <?=$id?>;

// when the DOM is ready
$(document).ready(function() {

    // 'click' because IE likes to choke on 'change'
    $('input[name=gender]').click(function(e) {

        // prevent normal, boring, tedious form submission
        e.preventDefault();

        // send it to the server out-of-band with XHR
        $.post('save.php?id=' + id, function() {
            data: $(this).val(),
            success: function(resp) { 
                if(resp == '1') {
                    alert('Saved successfully');
                } else {
                    alert('Oops, something went wrong!');
                }
            }
        });
    });
});
</script>

Solution 2

You can't do this with PHP alone ... you'll need some JavaScript on that page which executes onchanged of the radiobutton(s) and executes a PHP script. This is called Asynchronous JavaScript and XML or "AJAX", and a quick introduction would be http://www.w3schools.com/ajax/default.asp

Solution 3

+1 to karim79 for pointing out jQuery/AJAX and $_POST thingy. Very important.

Here is a solution without jQuery(if you are not interested in learning jQuery right now)

Step 1: Add an onchange even on your checkbox tags like this:

<p><label><input name="gender" type="radio" value="male" onchange="do_submit()" <?php if($_POST['gender']=='male'){?>checked="checked"<? }?> /> Male</label></p>
<p><label><input name="gender" type="radio" value="female" onchange="do_submit()" <?php if($_POST['gender']=='female'){?>checked="checked"<? }?> /> Female</label></p>

Step 3: Add a name attribute to form tag like this:

<form name="myform" action="check.php" method="post">

Step 3: Write the onchange event handler function in javascript:

<script type="text/javascript">
function do_submit() {
  document.forms['myform'].submit();
}
</script>

Couple of important things to note.

  • $_POST is a better option than $_REQUEST.
  • Use <?php instead of short form of php tag <?. It will be deprecated in future versions of php.
  • Investing time in learning jQuery/AJAX is 100% worth the time and effort
Share:
29,522
wow
Author by

wow

Help me (-_-;)

Updated on July 05, 2022

Comments

  • wow
    wow almost 2 years

    Example to save gender

    <form action="save.php?id=<?=$id?>" method="post">
        <p><label><input name="gender" type="radio" value="male" <?php if($gender=='male'){?>checked="checked"<? }?> /> Male</label></p>
        <p><label><input name="gender" type="radio" value="female" <?php if($gender=='female'){?>checked="checked"<? }?> /> Female</label></p>
    </form>
    

    Here an example to update the value

      if ($_REQUEST['gender']) {
      mysql_query("UPDATE users SET gender='$gender' WHERE id='" . $id . "'") or die(mysql_error());
      }
    

    How to make when we click on the gender the value will auto save to the db. Let me know.

  • karim79
    karim79 over 14 years
    Use the cody button with the 101010 in the input screen thingy.
  • karim79
    karim79 over 14 years
    @bob - that was just to provide additional insight, and hopefully spark some curiosity. Note, proper exception handling is missing and there's plenty of room for improvement (always!).
  • Mir Nazim
    Mir Nazim over 14 years
    karim79. I did and it correctly adjusts the code in the editor but does not works after submit :(
  • karim79
    karim79 over 14 years
    Ah, the numbered points screwed it up. I have yet to figure that out ;)
  • wow
    wow over 14 years
    yes always :) additional question. intval() better than (int)?
  • karim79
    karim79 over 14 years
    @bob - as far as I can tell, there's no difference, they both return a zero on failure. See php.net/manual/en/…