Blog

How to save data from a WordPress form to a database

Written by med

Saving data from a WordPress form to a database can be done in several ways. Here’s one method using PHP and MySQL:

  1. Create a database: First, create a MySQL database for storing the form data. You can use a tool like phpMyAdmin or MySQL Workbench to create the database and a table to store the form data.
  2. Create the WordPress form: Create a WordPress form using a plugin like Gravity Forms or Contact Form 7. Make sure to add fields that correspond to the columns in your database table.
  3. Set up a PHP script: Create a PHP script that will receive the form data and insert it into the database table. You can use the $_POST superglobal to access the form data and the mysqli extension to insert the data into the database.
  4. Configure the form settings: In the form settings, set the action attribute to the URL of the PHP script that you created in step 3.
  5. Test the form: Test the form by submitting it and checking that the data is being saved to the database.

Here’s an example PHP script that receives form data and inserts it into a MySQL database:

php
<?php
// Connect to the database
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabase";
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Insert form data into the database
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql = "INSERT INTO form_data (name, email, message) VALUES ('$name', '$email', '$message')";
if (mysqli_query($conn, $sql)) {
echo "Data saved successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

// Close the database connection
mysqli_close($conn);
?>

Make sure to replace yourusername, yourpassword, and yourdatabase with your actual database credentials. Also, update the SQL statement to match the columns in your database table.

About the author

med

Leave a Comment

(adsbygoogle = window.adsbygoogle || []).push({});