Add a Project
Learn how to use the “INSERT INTO” SQL statement.
We'll cover the following
The form
At the root of our project, we’ll add the project.php
file.
First, we’ll create a form like this:
<form method="post">
<label for="title">Title</label>
<input type="text" placeholder="New project" name="title" id="title">
<label for="category">Category</label>
<select name="category" id="category">
<option value="">Select a category</option>
<option value="Professional">Professional</option>
<option value="Personal">Personal</option>
<option value="Charity">Charity</option>
</select>
<input type="submit" name="submit" value="Add">
</form>
We need a little CSS
, so we’ve created a style.css
file in the root as well:
label {
display: block;
}
Form handling
Let’s treat our form.We’ll use the $_POST
method to get data for when the user submits the form. We’ll work with the following input: <input type="text" name="title"> will translate to $_POST['title']
.
The first thing we’ll do is to check whether the form was submitted:
if (isset($_POST['submit'])) {}
If the form was submitted, we can continue to work with the database connection in the try/catch
block because we are already accustomed to it.
Then, we’ll place the submitted form values into variables for later use:
if (isset($_POST['submit'])) {
try {
// db connection here
$title = trim($_POST['title']);
$category = $_POST['category'];
} catch {/*catch code here...*/}
}
We’ll use the trim()
function to delete white spaces.
Note:
You may have noticed that the data sanitization process was not carried out. This is because weplan to work with prepared statements. However, it is recommeneded that developers sanitize as much as possible, especially when writing:$title = trim($_POST['title'], FILTER_SANITIZE_STRING);
Now comes the SQL code, followed by the prepared statement and the value it is preparing ($sql
):
$sql = 'INSERT INTO projects(title, category) VALUES(?, ?)';
$statement = $connection->prepare($sql);
The ?
value is a placeholder that will be replaced by an exact value when the code is executed. We can also use named placeholders instead, like this:
$sql = 'INSERT INTO projects(title, category) VALUES(:title, :category)';
Before we execute the statement, we need to check that the user did not send any empty values:
if (empty($title) || empty($category)) {
$error_message = "Title or category empty";}
After verifying that there are no empty values, we’ll execute the statement with an array of all the submitted values:
$new_project = array($title, $category);
$statement->execute($new_project);
If we use a named placeholder, we can create our array like this:
$new_project = array(
'title' => $title,
'category' => $category
);
Here is the full PHP code:
Get hands-on with 1400+ tech skills courses.