Domanda

Esempio per salvare il genere

<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>

Ecco un esempio per aggiornare il valore

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

Come fare quando si fa clic sul genere il valore verrà salvato automaticamente nel db. Fammi sapere.

È stato utile?

Soluzione

Qualcosa per iniziare su un percorso più bello:

  // $_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;
          }
      }
  }

Supponendo lo stesso markup, una soluzione ajaxy (utilizzando 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>

Altri suggerimenti

Non puoi farlo con PHP da solo ... avrai bisogno di un po 'di JavaScript su quella pagina che esegue onchanged i pulsanti radio ed esegue uno script PHP. Questo è chiamato JavaScript asincrono e XML o & Quot; AJAX & Quot ;, e una rapida introduzione sarebbe http://www.w3schools.com/ajax/default.asp

Da +1 a karim79 per sottolineare jQuery / AJAX e $ _POST. Molto importante.

Ecco una soluzione senza jQuery (se non sei interessato a imparare jQuery in questo momento)

Passaggio 1: aggiungi un onchange anche sui tag della casella di controllo in questo modo:

<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>

Passaggio 3: aggiungi un attributo nome al modulo tag in questo modo:

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

Passaggio 3: Scrivi la funzione del gestore eventi onchange in javascript:

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

Un paio di cose importanti da notare.

  • $ _POST è un'opzione migliore di $ _REQUEST.
  • Usa <?php invece della forma abbreviata del tag php <?. Sarà deprecato nelle versioni future di php.
  • Investire tempo nell'apprendimento di jQuery / AJAX vale il 100% del tempo e dello sforzo
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top