Build a simple web application

let's build a simple web application that accepts user input and saves it to a MySQL database. Here's the step-by-step process:

  1. Create a database and table in MySQL: First, you need to create a database and table in MySQL. You can use any MySQL management tool like phpMyAdmin or MySQL Workbench for this. Let's assume we have created a database called "myapp" and a table called "users" with three columns - "id" (auto-increment), "name" (varchar) and "email" (varchar).

  2. Create a HTML form to accept user input: Create a HTML form with two input fields - "name" and "email" - and a submit button. You can use the following code to create the form:

HTML form (index.html):

<!DOCTYPE html>
<html>
<head>
	<title>Simple Form</title>
</head>
<body>
	<h1>Simple Form</h1>
	<form action="process.php" method="post">
		<label for="name">Name:</label>
		<input type="text" name="name" id="name">
		<br>
		<label for="email">Email:</label>
		<input type="email" name="email" id="email">
		<br>
		<label for="message">Message:</label>
		<textarea name="message" id="message"></textarea>
		<br>
		<input type="submit" value="Submit">
	</form>
</body>
</html>
  1. Create a PHP script to process the form data and save it to the database: Create a new PHP file called "process.php" and write the code to connect to the database and insert the user data into the "users" table. You can use the following code:

PHP process file (process.php):

<?php
// Connect to database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Insert form data into database
$sql = "INSERT INTO mytable (name, email, message) VALUES ('$name', '$email', '$message')";
if (mysqli_query($conn, $sql)) {
    echo "Form submitted successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

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

Note: Replace mydatabase, mytable, and database credentials with your own values. Also, make sure to save both files in the same directory on your XAMPP server.

Last updated