Pregunta

Ejemplo para guardar género

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

Aquí un ejemplo para actualizar el valor

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

Cómo hacer cuando hacemos clic en el género, el valor se guardará automáticamente en la base de datos. Avísame.

¿Fue útil?

Solución

Algo que te pone en una ruta más bonita:

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

Suponiendo el mismo marcado, una solución 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>

Otros consejos

No puede hacer esto solo con PHP ... necesitará algo de JavaScript en esa página que ejecute onchanged de los botones de radio y ejecute un script PHP. Esto se llama JavaScript asíncrono y XML o & Quot; AJAX & Quot ;, y una introducción rápida sería http://www.w3schools.com/ajax/default.asp

+1 a karim79 por señalar jQuery / AJAX y $ _POST cosita. Muy importante.

Aquí hay una solución sin jQuery (si no está interesado en aprender jQuery en este momento)

Paso 1: Agregue un cambio incluso en sus etiquetas de casilla de verificación 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>

Paso 3: Agregue un atributo de nombre para formar una etiqueta como esta:

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

Paso 3: Escriba la función del controlador de eventos onchange en javascript:

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

Un par de cosas importantes a tener en cuenta.

  • $ _POST es una mejor opción que $ _REQUEST.
  • Use <?php en lugar de una forma corta de etiqueta php <?. Será obsoleto en futuras versiones de php.
  • Invertir tiempo en aprender jQuery / AJAX vale el 100% del tiempo y esfuerzo
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top