Pergunta

Exemplo para salvar sexo

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

Aqui um exemplo para atualizar o valor

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

Como fazer quando clicamos sobre o sexo o valor será automaticamente salvar para o db. Deixe-me saber.

Foi útil?

Solução

Algo para ajustá-lo fora em um caminho mais bonito:

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

Assumindo a mesma marcação, uma solução ajaxy (usando 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>

Outras dicas

Você não pode fazer isso com PHP sozinho ... você vai precisar de algum JavaScript nessa página que executa onchanged do radiobutton (s) e executa um script PHP. Isso é chamado de Asynchronous JavaScript and XML ou "AJAX", e uma introdução rápida seria http: // www.w3schools.com/ajax/default.asp

+1 para karim79 por apontar jQuery / AJAX e $ _POST coisinha. Muito importante.

Aqui está uma solução sem jQuery (se você não estiver interessado em aprender jQuery agora)

Passo 1: Adicionar um onchange , mesmo em suas tags de caixa de seleção como esta:

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

Passo 3: Adicionar um nome atributo à tag forma como esta:

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

Passo 3: Escrever a função de manipulador de eventos onchange em javascript:

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

Algumas coisas importantes a nota.

  • $ _ POST é uma opção melhor do que $ _REQUEST.
  • Use <?php vez de forma abreviada de tag php <?. Ele será depreciado em futuras versões do PHP.
  • Investir tempo em aprender jQuery / AJAX é 100% vale a pena o tempo e esforço
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top