After you have created your database and tables as well as connecting to the database successfully, we proceed with the using this database to demonstrate how to insert data in the database. For this, we are going to use INSERT SQL command as well as mysqli_query function. But before we even start, we shall need two files i.e. the visitors.php file and the insert.php file. The visitors.php will have the form to be used by visitors to enter their name and feedback yet the insert.php will be the one to handle our insert logic.
visitors.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Official Website</title>
</head>
<body>
<h2>Your Feedback</h2>
<form action="insert.php" method="post">
<input type="text" name="username" placeholder="Your Name">
<textarea name="feedback" placeholder="Your Review"></textarea>
<button>Submit</button>
</form>
</body>
</html>
The above snippet is for the form to be used by the visitors to submit their names and feedback. As a quick review, you can revisit form handling post.
insert.php
<?php
include 'connect.php';
$visitor = $_POST["username"];
$feedback = $_POST["feedback"];
$sql = "INSERT INTO feedback (visitor, feedback) VALUES ('$visitor', '$feedback')";
if (mysqli_query($connect, $sql)) {
echo "Thank you for the feedback.";
} else {
echo "Error encountered.";
}
mysqli_close($connect);
?>
Let us start breaking down the code above. We start with the include keyword followed by ‘connect.php’. Include keyword in PHP is used to reference the codes in the specified file for our case, connect.php. The reason why we are referencing this file is because it is the one with our database connection codes and we created it here. Instead of repeating the same codes for database connection, we just reference the file that contains them. For us to be able to insert data into the database, we need a connection to the database.
We then move on to create the visitor and feedback variables holding information from the form on the visitor.php. You can review how we deal with form handling here. We afterwards write the SQL command for inserting data into the visitors table. To understand how we insert data, visit this post.
Finally the if statement is to help us confirm whether our data in being inserted into the database. We the mysqli_query function that takes two parameters i.e., the connection to database represented using $connect (in the connect.php file) and the insert SQL statement represented as $sql (just above the if statement).
If the database connection and insert SQL command are right, then a ‘Thank you for feedback’ message will be displayed i.e. data has been successfully inserted in the database. If either the connection or SQL command has a problem, return error encountered.
Finally we close off the connection to the database using mysqli_close function that has $connect (in the connect file). That is how it is so easy to insert data into the database using PHP 🥳