29415

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

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.

Answer1:

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>

Answer2:

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

Answer3:

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

<strong>Step 1:</strong> Add an <strong>onchange</strong> 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>

<strong>Step 3:</strong> Add a <strong>name</strong> attribute to form tag like this:

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

<strong>Step 3:</strong> 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.

    <li>$_POST is a better option than $_REQUEST.</li> <li>Use <?php instead of short form of php tag <?. It will be deprecated in future versions of php.</li> <li>Investing time in learning jQuery/AJAX is 100% worth the time and effort</li> </ul>

Recommend

  • Fast Fourier Transform results: frequency axis scale?
  • element-wise count along axis of values in numpy array
  • PHP Regexp on filename and number - preg_replace_callback
  • Do I need to clean user input for DB::query calls in laravel?
  • How do you start a batch file in the background and redirect its output?
  • SimpleXML - echo / print_r return different values
  • Unable to retrieve full text of title from JPEG metadata
  • file_get_Contents won't send query strings in url , thus receiving nothing with $_GET
  • Collect and run all junit tests in parallel with each test class in its own JVM (parallelization by
  • Quickly or concisely determine the longest string per column in a row-based data collection
  • Index.php as custom error page
  • Do I have to inject the service in the unit test if I cal testBed.get() previously?
  • MonadTransControl instance for ProxyFast/ProxyCorrect
  • Divide a $1 by 3 and adjusting 1 cent
  • iOS Cordova first plugin - plugin.xml to inject a feature
  • How to use function wrapper in mustache.php?
  • Detecting null parameter in preprocessor macro
  • How to 'create temp table as select' in Slick?
  • what makes a request a new request in asp.net C#
  • Eliminate partial duplicate rows from result set
  • pyodbc doesn't report sql server error
  • Spring Cloud Microservice Architecture Confusion
  • System.InvalidCastException: Specified cast is not valid
  • How can I extract results of aggregate queries in slick?
  • OOP Javascript - Is “get property” method necessary?
  • Transactional Create with Validation in ServiceStack Redis Client
  • Handling un-mapped Rest path
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • Counter field in MS Access, how to generate?
  • angularjs unit test when to use $rootScope.$new()
  • Join two tables and save into third-sql
  • How to handle AllServersUnavailable Exception
  • Upload files with Ajax and Jquery
  • php design question - will a Helper help here?
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • AngularJs get employee from factory
  • Angular 2 constructor injection vs direct access
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Authorize attributes not working in MVC 4
  • Bitwise OR returns boolean when one of operands is nil