Mada za sehemu hiiLinking forms to databases for interactive web applicationsMada 3
- Implementing insertion of form data into a database
- Implementing retrieval and display of data from a database
- Implementing updating and deletion of data in a database
Implementing Insertion of Form Data into a Database
When users submit information through a web form, that data must be saved into a database so the application can store and retrieve it later. This process is called data insertion, and it is one of the basic operations every interactive web application needs.
Before inserting data, remember that databases support four main operations, together known as CRUD:
- Create — adding new records (this is what we learn today)
- Read — viewing or searching existing records
- Update — changing existing records
- Delete — removing records
Inserting form data into a database is the Create part of CRUD. Without it, users cannot save their information.
To insert data, your PHP script must first connect to the database server. The basic steps are:
- Define connection details (server name, username, password, database name)
- Create a connection using
mysqli_connect() - Check if the connection succeeded
- Use the connection to run SQL commands
$server = "localhost";
$username = "root";
$password = "";
$database = "school_db";
$conn = mysqli_connect($server, $username, $password, database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
This code connects to a MySQL or MariaDB database running on the same computer.
The user enters data through an HTML form. Each input field corresponds to a column in your database table.
<form action="insert.php" method="POST">
<label>Full Name:</label>
<input type="text" name="fullname" required>
<label>Email:</label>
<input type="email" name="email" required>
<button type="submit">Register</button>
</form>
The method="POST" attribute sends the data securely to the server. The form submits to a PHP file called insert.php, which will handle the insertion.
Prepared statements are the safe way to insert data. They protect your application from SQL injection attacks, where hackers try to inject harmful code through form inputs.
Step-by-step process:
- Write an SQL
INSERTstatement with placeholders (?) - Prepare the statement
- Bind the form values to the placeholders
- Execute the statement
// Get form data
$fullname = $_POST['fullname'];
$email = $_POST['email'];
// Write SQL with placeholders
$sql = "INSERT INTO users (fullname, email) VALUES (?, ?)";
// Prepare and execute
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ss", $fullname, $email);
if (mysqli_stmt_execute($stmt)) {
echo "Registration successful!";
} else {
echo "Error: " . mysqli_error($conn);
}
// Close statement and connection
mysqli_stmt_close($stmt);
mysqli_close($conn);
The "ss" in bind_param means both variables are strings. Use "i" for integers and "d" for decimal numbers.
Consider a Tanzanian secondary school that wants to register new students online. The database table students has three columns: id (auto-increment), name, and class.
HTML form (register.html):
<form action="save_student.php" method="POST">
<h2>Student Registration</h2>
<input type="text" name="student_name" placeholder="Enter student name" required>
<input type="text" name="student_class" placeholder="Enter class (e.g., Form I)" required>
<button type="submit">Save Student</button>
</form>
PHP handler (save_student.php):
$conn = mysqli_connect("localhost", "root", "", "school_db");
$name = $_POST['student_name'];
$class = $_POST['student_class'];
$sql = "INSERT INTO students (name, class) VALUES (?, ?)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ss", $name, $class);
if (mysqli_stmt_execute($stmt)) {
echo "Student saved successfully!";
} else {
echo "Failed to save student.";
}
mysqli_close($conn);
When the form is submitted, the student's name and class are saved into the students table in the database.
In Tanzania, small businesses like shops in Dar es Salaam or moriani (local markets) in Arusha use simple web forms to record new customers or track inventory. For example, a duka la vifaa vya mboga (vegetable shop) can use a registration form to save a customer's phone number and purchases into a database, then later check what each customer bought and how much they owe — helping the owner manage payments and keep track of sales without writing everything in a notebook.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
- Create forms with fields mapped to database columns.
- Write PHP scripts to open and close database connection
- Write PHP scripts to insert form data into a database.
- Use prepared statements for secure data insertion.
Tathmini ya matokeo
Functional forms that successfully insert data into a database (e.g., user records, product entries).
Tathmini ya maarifa
Detailed knowledge of:
Method used: The student should explain how to
- use INSERT SQL commands with PHP scripts to add data to a database
- Open and close database connection
Principles: The student should explain the principles of:
- secure database connectivity
Theories: The student should explain:
- Concepts of database connectivity using PHP
Circumstantial knowledge:
Detailed knowledge about:
- error handling during database insertion (e.g., handling duplicate entries, logging failed inserts).
Swali
What does the "C" stand for in the CRUD operations used in databases?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado