PHP MySQL insert form data into a MySQL database
To insert form data into a MySQL database using PHP with procedural style, follow these steps:
Step-by-Step Process:
- Create the HTML form: Collect user inputs via an HTML form.
- Capture form data: Use
$_POST
(for POST method) to capture the form data. - Establish a connection to MySQL: Use
mysqli_connect()
to connect to your MySQL database. - Prepare the SQL Insert Query: Construct a SQL
INSERT INTO
statement to insert the data. - Execute the SQL query: Use
mysqli_query()
to execute the query. - Close the connection: Always close the database connection using
mysqli_close()
.
Example:
1. Create the HTML form
<form action="insert.php" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required>
<input type="submit" value="Submit">
</form>
2. Capture form data in insert.php
<?php
// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Capture the form data
$name = $_POST['name'];
$email = $_POST['email'];
// Step 1: Establish connection to MySQL
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check if connection was successful
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Step 2: Prepare the SQL query
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
// Step 3: Execute the query
if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully!";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Step 4: Close the connection
mysqli_close($conn);
}
?>
Key Points:
Security Note: In the above example, raw input from the user is directly used in the query. To prevent SQL injection attacks, always sanitize input or use prepared statements.
For example, use:
$name = mysqli_real_escape_string($conn, $_POST['name']);Error Handling: Always check for potential errors in connection and query execution.
Database Structure: Make sure you have a database (
test_db
) and a table (users
) with the appropriate columns (name
,email
).
Here’s how the table might look:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);