Learn how to create dynamic websites and applications with fun, hands-on PHP exercises.
| Member ID | First Name | Last Name | Age | Gender | Relationship |
|---|---|---|---|---|---|
| ’ . $row[‘MemberID’] . ‘ | ’ . $row[‘FirstName’] . ‘ | ’ . $row[‘LastName’] . ‘ | ’ . $row[‘Age’] . ‘ | ’ . $row[‘Gender’] . ‘ | ’ . $row[‘Relationship’] . ‘ |
’; But what if there was no response for the database because something went wrong? That could happen. In that case we add an else statement after our ifstatement to display the error message using the mysqli_error function and we pass in our connection as a parameter: else{ echo “Cound not get a response from database ” . mysqli_error($conn); } Lastly, we close the database connection using the mysqli_close function, passing in the connection as a parameter and we are done with the index page: mysqli_close($conn); Go into the browser and enter that path to the index.php as follows then press Enter: https://localhost/Family/index.php The below window should display: As you can see; it is displaying the records we entered previous and has generated the table dynamically. Neat huh! CSS for index Page Create a folder inside the websites root folder called css and create two CSS files called main.css and table_styling.css. These are the external style sheets for the page. We enter the following code into main.css to style the body, headers, and links. It also centers the content: body { background-color: #EEE; } #container { width: 900px; margin-left: auto; margin-right: auto; } #header { color: #2ca089; text-align: center; font-size: 2em; } /* links */ a:link, a:visited { background-color: #2ca089; color: white; padding: 5px 12px; text-align: center; text-decoration: none; display: inline-block; } a:hover, a:active { background-color: #AFDCB1; } #btn_add { padding: 5px 0px; text-align: right; } Then we enter the following code into table_styling.css to style the table: table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even){background-color: white; } th { background-color: #2ca089; color: white; } Creating the Form to Input Data We create a file called form.php and place it the root folder of the website. Then we place the code below:
Nothing out of the ordinary is happening here. This just your basic HTML form which we will use to send the data inputted into the fields to the database. The form has the two attributes which are of interest to us: form action - This tells the form to send the form-data to the member_added.php script(which we shall create in a moment) that will process the information when the ADD button is pressed method = “post” – Tells the form to send the form-data as an HTTP post transaction. This means that the data is appended inside the body of the HTTP request URL. This is good for sending sensitive data (things like passwords) unlike the “get” method which just appends the data to the URL and anyone one can see it. Go into the browser and display the index page. Click the ADD button at top right of the table and the following page should display with the form to add family members: CSS for Form Page Create a CSS file called form_stlying.php and place it in the root directory of the website. Place the following style rules in that file to style the form using this external style sheet: input[type=text], input[type=number], select { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } input[type=submit] { width: 100%; background-color: #2ca089; color: white; padding: 14px 20px; margin: 8px 0; border: none; border-radius: 4px; cursor: pointer; } input[type=submit]:hover { background-color: #2ca089; } Creating the Member Added Page Finally, you need to create one final PHP script for to process the data sent by the form. We create a new PHP script and called member_added and place in the root directory of our website. Then we place the following code in the script:
Let us break this down and look at the most interesting bits.
We have to check if the information was submitted by the form before we work with it.
We do this with an if statement and use the isset() built in PHP function that checks if a
variable is null. We pass in the associative array $_POSTas a parameter. It contains all
values inputted into the form found in form.php. The array is passed to the script via the
post method of the form:
if(isset($_POST[‘submit’])) {
}
Inside the conditional statement, we then declare an array to check if we happen to have
missed any if the form inputs:
$null_fields = array();
Next we start checking if any the values in the array are empty before we send them to the
database. If so, we add them to the $null_fields array if not, we create a variable and store
them there. We will just look at one of the if…else statements because the rest a similar:
if (empty($_POST[‘first_name’])) {
$null_fields[] = ‘First Name’;
} else {
$first_name = trim($_POST[‘first_name’]);
}
We do this for the rest of values in the $_POST array.
Warning: This may not be the most secure way of verifying data before it goes to the
database. For that we need to use regular expressions and that is an advanced topic. We
are just trying to keep things simple.
Next we have to check if the $null_fields array turned out empty. This means all the data
was submitted:
if (empty($null_fields)) {
}
If we are inside that condition, it means that all the data was submitted and we can query
the database. We use the INSERT TO statement to insert the data into the
FamilyMembers table. We follow the rules used to insert data into a table by making sure
the variables are in the same order as they are defined in the tables. We declared an extra
variable before the creating the query string to pass in as a null value for the primary. We
also make sure the number of parameters match the number of fields in the table:
$null_variable = NULL;
$sql = “INSERT INTO FamilyMembers VALUES (‘$null_variable’, ‘$first_name’,
‘$last_name’, ‘$age’, ‘$gender’, ‘$relationship’)”;
Next, we use query database using the mysqli_query(), passing in the connection and
query string as parameters, while simultaneously checking for any errors return by the
function. It returns FALSE on failure. If errors are found, we display them so they can be
fixed. If not errors are found, we echo a success message:
if (!mysqli_query($conn, $sql)) {
die (‘Error: ‘ . mysqli_error($conn));
}else {
echo “Family member has been entered!”;
}
So now we are done with what happens when the player inputs all the data, but if he
misses any, we should display to him the fields he missed by looping through the
$null_fields array using a foreach loop and echoing them to the screen.
else {
echo “You need to enter the follwing missing data:
”;
foreach ($null_fields as $null_field) {
echo $null_field . “
”;
}
}
Then after that, we exit the condition that checks if the $_POST array is empty and close
the connection to the database:
mysqli_close($conn);
Then right after the closing PHP tag we display the form again that allows for the PHP
script to call itself so that we can continue inputting data or re-enter data in case we forgot
some fields.
And we are done! Now we should be able to add family members and view them. We
should also be able to navigate between pages using the buttons on the top right corner of
the forms or table that allow you switch between the pages.
Start up the index page and go to the form page to add some data
Click the ADD button to add the member to database. You should see the success
message:
Click the View Members button to verify. The below window should display with the new
member added:
Summary
So there you have it! Before this chapter we looked at PHP and MySQL separately and in this chapter was aimed at
consolidating the two, and showing how to use them to produce dynamic content. It should not be that hard to modify
the website to do whatever you need it to do as you are now capable.
In the chapter we created a configuration file that stored the connection to the database and used it all throughout the
website to establish a connection to the database and query it to store and retrieve data. We created a page that enables
you to view information about the family members you have added to database. We also created a page with a form for
inputting the data and a page that has the PHP needed to process the data when the form is submitted.
Conclusion
“Education is the kindling of a flame, not the filling of a vessel.” ― Socrates
This is the end of this book, but not your learning. You still have to go out there and learn
what other things you can do with PHP and MySQL and get a more in depth
understanding of the concept. At this point though, I sincerely hope you have been
equipped with enough knowledge to do what is you need to do with a basic understanding
of PHP and MYSQL.
In the first hour, we covered the basics of PHP like comments, variables, constants and
operators. But not before we learned how to install the server package XAMPP to that has
the Apache service for the server. We run a PHP script and displayed neat messages to the
screen. We also chose a cool text editor to write beautiful PHP code.
In second hour, we got a little deeper into the basics of PHP and looked at how we can
write conditional statements that allow us to execute blocks of code depending on a
specified condition. Next we looked at how to loop thorough code until a certain condition
is met using while and for loops. We then looked at how we encapsulated code blocks and
re-use them through the program using functions. We passed information to the in the
form of parameters and they return some of it back after performing operations on that
information. Then we finally we saw how to store collections of data into arrays and how
to loop through them.
In the third, hour we learned MySQL. We learned how to bring up the command prompt to
enter MySQL commands to perform various operations such as creating and deleting
databases; creating, altering and deleting tables; retrieving, inserting, updating and
deleting the data in the tables.
In the fourth and final chapter we looked at how we can use PHP and MySQL together to
create dynamic content for a simple website we were making a list of our favorite family
members and their details.
All this is knowledge for the absolute beginner who needs something to quickly guide
them with clear examples and explanations. I wish you well in your futures endeavors and
I believe you are well on your way to achieving your dreams. Glad I could help.