First, you need to create a database and a table to store the form data. You can use phpMyAdmin or command-line tools to execute the following SQL commands:
CREATE DATABASE form_db; USE form_db; CREATE TABLE form_data ( id INT(11) AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, message TEXT );
Next, create a simple HTML form where users can input their name, email, and message:
<form method="POST" action="submit.php"> <label for="name">Name:</label> <input type="text" name="name" id="name" required><br> <label for="email">Email:</label> <input type="email" name="email" id="email" required><br> <label for="message">Message:</label> <textarea name="message" id="message" rows="5" required></textarea><br> <input type="submit" value="Submit"> </form>
Create a PHP file named submit.php to receive the form data and insert it into the database:
<?php // Get form data $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; // Connect to the database $connection = mysqli_connect('localhost', 'username', 'password', 'form_db'); // Check connection if (!$connection) { die("Database connection failed: " . mysqli_connect_error()); } // Insert data $sql = "INSERT INTO form_data (name, email, message) VALUES ('$name', '$email', '$message')"; if (mysqli_query($connection, $sql)) { echo "Data successfully inserted into the table."; } else { echo "Error inserting data: " . mysqli_error($connection); } // Close connection mysqli_close($connection); ?>
After uploading both the HTML form and PHP script to your server, open the form page in your browser, fill in the details, and submit. If everything is set up correctly, you will see a message confirming the data was successfully inserted.
This tutorial covered the basics of submitting form data to a MySQL database using PHP. The process included creating the database and table structure, building the user form, and writing the PHP script to handle data insertion. In real-world applications, you should also add data validation, sanitization, and security measures to make your application more robust and secure.