Inserting Data into MySQL from PHP Using jQuery/AJAX
In this guide, we will explore how to leverage PHP and jQuery/AJAX to insert data from a basic HTML form into a MySQL database.
Understanding the Form
Let's assume you have a form with the following structure:
<code class="html"><form method="post" action="process.php" onSubmit="return ajaxSubmit(this);"> Value: <input type="text" name="my_value" /> <input type="submit" name="form_submit" value="Go" /> </form></code>
jQuery/AJAX Script
This script will handle sending the form data to the server via an AJAX request:
<code class="javascript"><script type="text/javascript"> var ajaxSubmit = function(formEl) { var url = $(formEl).attr('action'); var data = $(formEl).serializeArray(); $.ajax({ url: url, data: data, dataType: 'json', success: function(rsp) { if(rsp.success) { alert('Form has been posted successfully.'); } } }); // Prevent the form from submitting to the page return false; } </script></code>
Processing Script (process.php)
This PHP script will connect to the database and insert the submitted data:
<code class="php"><?php function post($key) { if (isset($_POST[$key])) return $_POST[$key]; return false; } // Connect to the database $cxn = mysql_connect('localhost', 'username_goes_here', 'password_goes_here'); if (!$cxn) exit; mysql_select_db('your_database_name', $cxn); // Escape the form input $val = mysql_real_escape_string(post('my_value'), $cxn); // Insert query $sql = sprintf("INSERT INTO %s (column_name_goes_here) VALUES '%s';", 'table_name_goes_here', $val ); // Execute query $result = mysql_query($sql, $cxn); // Set response object $resp = new stdClass(); $resp->success = false; if($result) { $resp->success = true; } print json_encode($resp); ?></code>
Usage
Note: This code is provided for guidance only and may require modifications to work in your specific environment.
The above is the detailed content of How to Insert Data into a MySQL Database from a PHP Form Using jQuery/AJAX?. For more information, please follow other related articles on the PHP Chinese website!