PHP + MySQL + CSS CRUD (Procedural)
Lession 3: Add Student (CREATE)
๐ Introduction
In this lesson, students will learn how to add new student records to the database using MySQLi procedural programming. This is the โCโ in CRUD โ CREATE. We will build a form using Bulma CSS and write PHP code to insert data into the database.
๐ Step 1: Create the Add Student Form
We begin by creating a new file named create.php. This file contains a Bulma-styled form
that collects student information.
<form action="" method="POST">
<div class="field">
<label class="label">Name</label>
<input class="input" type="text" name="name" required>
</div>
<div class="field">
<label class="label">Email</label>
<input class="input" type="email" name="email" required>
</div>
<div class="field">
<label class="label">Phone</label>
<input class="input" type="text" name="phone" required>
</div>
<button class="button is-primary" name="submit">Save</button>
</form>
๐ง Step 2: Capture Form Data
When the form is submitted, PHP receives the values using the $_POST superglobal.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
These variables will be inserted into the database.
๐๏ธ Step 3: Insert Data into MySQL
We use the INSERT INTO SQL command to add a new record.
$sql = "INSERT INTO students (name, email, phone, created_at)
VALUES ('$name', '$email', '$phone', NOW())";
mysqli_query($conn, $sql);
The NOW() function automatically stores the current timestamp.
๐ Step 4: Redirect After Saving
After inserting the record, redirect the user back to the main page.
header("Location: index.php");
exit;
๐ง Syntax Breakdown
$_POSTโ retrieves form input values.INSERT INTOโ SQL command to add new data.mysqli_query()โ executes SQL commands.NOW()โ MySQL timestamp function.header()โ redirects the user.
๐งช Exercise
Add a new field called address to the form and database. Update:
- The MySQL table
- The form
- The PHP insert query
Test your changes by adding a new student with an address.
Edit the panels below and press Run to preview. Nothing you type here is saved โ refreshing the page restores the original starter code.