Home > Database > Mysql Tutorial > body text

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

Barbara Streisand
Release: 2024-11-02 09:57:30
Original
396 people have browsed it

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

Inserting into MySQL from PHP Using jQuery/AJAX

Inserting data from a web form into a MySQL database using PHP and AJAX with jQuery can initially seem daunting. However, with a simple example, we can break down the process into manageable steps.

Form and jQuery Code

Our HTML form consists of a text input for user input and a submit button:

<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>
Copy after login

Here, process.php is the PHP script that handles the data submission. The jQuery function ajaxSubmit is called on form submission. It serializes form data into an array data and sends an AJAX request to the process.php script, carrying the data.

The Process Script

The PHP script process.php performs the following tasks:

  1. Import form data using the post() function: $val = mysql_real_escape_string(post('my_value'), $cxn);
  2. Sanitize the data to prevent SQL injection: $val = mysql_real_escape_string($val, $cxn);
  3. Establish a MySQL connection using $cxn = mysql_connect(...) and select the target database.
  4. Build a MySQL INSERT query using the form data: $sql = sprintf("INSERT INTO ...VALUES '%s';", $val);
  5. Execute the query using $result = mysql_query($sql, $cxn);
  6. Create a response object with a success flag and encode it into JSON: $resp = new stdClass(); $resp->success = true; print json_encode($resp);

AJAX Response Handling

The AJAX request in jQuery checks the server response for success and displays an alert accordingly. Upon successful form submission, an alert notifies the user and the form can be reset.

With these components in place, you can insert data from your web form into a MySQL database seamlessly and handle responses using jQuery/AJAX.

The above is the detailed content of How to Insert Data into a MySQL Database from a Web Form Using PHP and jQuery/AJAX?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template