Skip to content
Chapter 05 of 05 · 2 lessons · ~22 min

PHP and MySQL

Connect to a MySQL database with PDO and save your contact form messages safely with prepared statements.

YOUR PROGRESS0%
/ Lessons in this chapter
13
How to Connect PHP to MySQL (PDO) How to create a MySQL database and connect to it from PHP with a secure, reusable PDO connection. Coming soon
14
Save Form Data to a MySQL Database With PHP How to insert form data safely with prepared statements and finish the course project: a contact form that validates, saves and emails every message. Coming soon

Chapter practice task

Task: Save every contact form message to a MySQL table and list them on a private page

  1. Create a database and a messages table in phpMyAdmin.
  2. Connect with PDO from a db.php file, with credentials in your config.
  3. Insert each valid form submission with a prepared statement.
  4. Build a password-protected messages.php page that lists the latest 50 messages, escaped.

By the end of this chapter

  • You can create a database and table in phpMyAdmin
  • You can connect to MySQL with PDO and handle connection errors properly
  • You can insert and read data with prepared statements, safe from SQL injection
  • You have a finished contact form that validates, emails and saves every message

Quick answers for this chapter

PDO or MySQLi?

PDO. It has a clean API, named placeholders and works with other databases too.

What is SQL injection?

An attack where user input changes your SQL query. Prepared statements prevent it completely when you use them for every value.

Where do I find my database details on Hostinger?

In hPanel under Databases → Management. Create a database and user there, and use the host it shows (often localhost).