PHP + SQL Demo: Simple Form with Database Insert

Welcome to Projects
This demo showcases a simple PHP + SQL form that inserts user data into a database. Whether you’re just starting out in development or refreshing your backend skills, this lab will help you understand the fundamentals of handling form data securely and efficiently.

Let’s dive into the code and see how the magic happens!

<!-- index.php -->
<form method="post" action="insert.php">
  <label for="name">Name:</label><br>
  <input type="text" id="name" name="name" required><br><br>
  
  <label for="email">Email:</label><br>
  <input type="email" id="email" name="email" required><br><br>
  
  <input type="submit" value="Submit">
</form>
<!-- insert.php -->
<?php
$servername = "localhost";
$username = "root"; // change as needed
$password = ""; // change as needed
$dbname = "demo_db"; // make sure this DB exists

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Sanitize inputs
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);

// Prepare and bind
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $stmt->error;
}

$stmt->close();
$conn->close();
?>


Stay tuned—next time we’ll connect this form to a hosted SQL database and sanitize inputs using prepared statements. This is just the beginning of your full-stack journey!

© 2012–2025 Jet Mariano. All rights reserved.
For usage terms, please see the Legal Disclaimer.

error: Content is protected !!