Home  >  Article  >  Database  >  How to Insert Data into a MySQL Database from a PHP Form Using jQuery/AJAX?

How to Insert Data into a MySQL Database from a PHP Form Using jQuery/AJAX?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 16:16:02960browse

How to Insert Data into a MySQL Database from a PHP Form Using jQuery/AJAX?

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

  1. Save the form and jQuery/AJAX script in an HTML file.
  2. Save the processing script as "process.php".
  3. Submit the form to trigger the AJAX request and insert the data into the database.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn