Read and write MYSQL database using PHP
Step 1: Create the Database and Table
Run the following SQL commands in your MySQL database:
CREATE DATABASE form_example;
USE form_example;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);
Step 2: Create the PHP Form (form.html)
Create an HTML file (form.html) with a simple form for data entry:
<!DOCTYPE html>
<html>
<head>
<title>Simple PHP Form</title>
</head>
<body>
<h2>Submit Your Information</h2>
<form action="submit.php" method="post">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Step 3: Create the PHP Script (submit.php)
This PHP script processes the form data and inserts it into the MySQL database:
<?php
// Database configuration
$servername = "localhost"; // Change this if your MySQL server is on a different host
$username = "root"; // MySQL username
$password = ""; // MySQL password
$dbname = "form_example"; // Name of the database
// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
// Check if form data has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
// Prepare an SQL statement to prevent SQL injection
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the query
if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $stmt->error;
}
// Close the statement and connection
$stmt->close();
$conn->close();
?>
Step 4: Create the PHP Script to Retrieve Data (retrieve.php)
Create a new PHP file (retrieve.php) that connects to the database, fetches the records, and
displays them in an HTML table:
<?php
// Database configuration
$servername = "localhost"; // Change this if your MySQL server is on a different host
$username = "root"; // MySQL username
$password = ""; // MySQL password
$dbname = "form_example"; // Name of the database
// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
// SQL query to retrieve data
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
// Check if there are results and display them
if ($result->num_rows > 0) {
echo "<h2>Retrieved User Information</h2>";
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
// Output data of each row
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['name'] . "</td><td>" .
$row['email'] . "</td></tr>";
echo "</table>";
} else {
echo "No records found.";
// Close the connection
$conn->close();
?>