Web Development 1 - Lecture 2 - PDO
Web Development 1 - Lecture 2 - PDO
1
Contents
• Options for working with databases
• Advantages of using PDO
• Managing a MySQL database
• Creating a guestbook
• Connecting to the database
• Selecting and displaying data
• Inserting data
• Sanitizing inputs
2 Web Development 1
Discussion
In PHP, we have lots of options for working with databases.
- Which database systems do we know? 💡
We can divide our options into these three:
1. Use a relational database, such as MySQL/MariaDB, with PDO
2. Use an OR/Mapper (ORM), such as doctrine, with a relational database
3. Use a NoSQL database, such as MongoDB
What are the differences between these choices? Can you think of more options?
3 Web Development 1
Why use PDO?
PDO provides an object-oriented way to access relational databases.
• Contrary to MySQLi, it can connect to multiple database systems, such as
MySQL, PostgreSQL, Oracle, MS SQL Server, SQLite and more.
• It supports parameterized queries (prepared statements with bound
parameters)
• It can load data directly into objects or associative arrays
• Conceptually, PDO works a lot like ADO.NET which you have used in your
C# projects
4 Web Development 1
Previous lecture
Previously, we discussed:
• How to generate HTML output
• How to read data from the URL
• How to read data from a posted form
If we combine this knowledge with what we know about HTML, SQL and, by
the end of this lecture, PDO, we should be able to create CRUD functionality
in a PHP application.
5 Web Development 1
Managing a MySQL database
Most PHP web applications use MySQL or MariaDB (open-source fork).
PHPMyAdmin is an open-source database management tool, written in PHP
(it can run on your local development server as a web application!)
6 Web Development 1
Assignment: Guestbook database
Let’s create a new database and call it ‘guestbook’.
You should be able to figure this out.
Then add a table named ‘posts’, it will have 6 columns:
• id (int), turn on A_I and set Index to PRIMARY
• posted_at (datetime)
• name (varchar, specify the length)
• email (varchar, specify the length, allow null values)
• message (varchar, specify the length)
• ip_address (what datatype should we use and why?)
And
7
finally, add some test messages to the table
Web Development 1
Assignment result:
Your table should look like this:
Note how the naming convention for columns in MySQL is lowercase, with
underscores instead of spaces.
8 Web Development 1
Assignment result:
The ‘Insert’ tab can be used to add some test data.
A few test messages are needed, so we can read and display these using PHP
MakeWeb
9 sure to explore
Development 1 PHPMyAdmin when you have the time!
Connecting to the database
Goal: display all guestbook messages on a page.
Let’s create a file called dbconfig.php and store our database connection
settings in some variables.
10 Web Development 1
Connecting to the database
Then, we will add an index.php file where we:
- Include/require our database configuration file
- Create a PDO connection object
11 Web Development 1
Posting data
We can use the query method on the connection object to execute a query without
parameters. A very simple example would be:
$result now contains the result object, which is an associative array. We can simply loop
through it and display the values. Try it out!
12 Web Development 1
Assignment
Make your page look like this (or better 😉)
13 Web Development 1
Time for a break
(and maybe catch up, or ask questions)
Inserting data
We will add a simple form to our guestbook, this will allow people to add posts.
15 Web Development 1
Pseudocode
The complete page script will work like this:
1. Establish database connection
2. Check if the form was submitted
A. If it was, insert the data into the database
B. If it was not, just continue
16 Web Development 1
Check for a POST request
2 ways are often used to check if a form was submitted. Either we can check if the current
request is a POST request:
17 Web Development 1
Inserting data
INSERT queries require parameters. The PDO way to do this is to create a prepared
statement:
Note we are using the mysql now() function to insert the current date/time instead of letting
PHP determine the value.
Read more about prepared statements here:
PHP: Prepared statements and stored procedures - Manual
18 Web Development 1
Inserting data
Then, we can bind (link) the parameters in the prepared statement to variables.
And finally execute the query:
19 Web Development 1
Query parameters
But why did we use parameters?
We could just have written:
$connection->query(“INSERT INTO posts (name, message, posted_at,
ip_address) VALUES ($name, $message, now(), $_SERVER[‘REMOTE_ADDR’]”);
So, why all the hassle with extra code?
20 Web Development 1
But wait…
Try to submit the following message:
<script>location.href =
"https://lmgtfy.app/?q=my+website+has+been
+hacked";</script>
What happens?
What happens if you visit your guestbook again later?
21 Web Development 1
XSS
We have just seen JavaScript injection, this is an important security risk and a way to do
Cross-Site Scripting (XSS) attacks.
It should never be possible to inject code in your application!
Always sanitize your inputs.
No harm done 👌
22 Web Development 1
XSS
You can sanitize the entire $_POST array in one line of code:
23 Web Development 1
Summary & next steps
Today, you learned:
• What PDO is and how to work with MySQL/MariaDB
• using phpmyadmin to create and manage tables
• executing a select query and displaying the data
• processing a submitted form and storing the sent data in the database
• sanitizing the input
• figuring out how to do the U and D from CRUD is still up to you
24 Web Development 1
Homework
Extend our guestbook page with a management page.
• Show all posts in a table
• Show all the data (so also the id and the ip address)
• Give every post a button or link to delete it. Get this working!
Challenge mode 💥
• Make sure the management page is only accessible after logging in with a username &
password. For this you will most likely need $_SESSION.
• Give every post an edit link/button, that allows you to edit posts.
How you do this is completely up to you. Have fun!
We will review the code in the next lecture!
25 Web Development 1
Any questions?
26 Web Development 1