Guide
Working with Forms and Databases in PHP: Core Concepts
Learn how PHP handles HTML forms and databases: GET and POST, validation, PDO and MySQLi, CRUD operations, and the safe way to store and show data.
Key takeaways
- GET puts data in the address and suits searches; POST sends data in the request body and suits actions that change something.
- Always validate on the server, because browser checks can be bypassed.
- Use prepared statements for every query that includes outside values, and escape stored text when you display it.
- PDO works with many databases through one interface, while MySQLi is specific to MySQL.
- CRUD means create, read, update and delete, the four basic actions on stored data.
Why forms and databases come together
Most real websites collect information from visitors and store it. A contact page, a registration screen, an order form and a comment box all follow the same journey: the visitor fills a form, the browser sends the data to the server, PHP checks it, a database stores it, and the site later shows it again. Understanding this chain is the heart of practical PHP development.
How do HTML forms send data to PHP?
A form in HTML has fields such as text boxes, drop-down lists, check boxes and buttons. The form also declares where to send the data and which method to use. With the GET method the data is placed in the address, which makes the result bookmarkable and suits searching and filtering. With the POST method the data travels in the body of the request, which suits actions that create or change something, such as registering or placing an order. Large submissions and file uploads also use POST.
On the server, PHP collects the submitted values in special arrays for GET and POST data, and uploaded files are described in another array. Remember that every value arrives as text and comes from outside your control, so it must never be trusted.
How should input be validated?
Validation means checking that the data has the expected shape: a required name is not empty, an email address looks like an email address, an age is a sensible number, and a chosen option is one of the options you offered. Do validation on the server even if the browser also checks, because browser checks can be bypassed. PHP includes a filter extension that can check common formats, and you can add your own rules for business needs.
Keep validation and escaping separate in your mind. Validation decides whether the data is acceptable. Escaping prepares data for a specific destination, such as HTML output or a database query. Using the right tool at the right point is what keeps a site safe.
Giving helpful feedback
When validation fails, return the visitor to the form with clear messages next to the fields that need correction and keep the values already entered. A frustrating form that clears everything is a common reason for lost enquiries. After a successful submission, a good habit is to redirect to a thank-you page, so that refreshing the browser does not send the form twice.
Which database should you choose?
PHP works with many databases, and MySQL and MariaDB are very common in hosting plans. PostgreSQL and SQLite are also popular. A relational database stores data in tables made of rows and columns, and you talk to it with SQL, a language for creating, reading, changing and deleting records.
Should you use PDO or MySQLi?
There are two main extensions for relational databases. PDO offers one consistent interface for many database systems. MySQLi is specific to MySQL and MariaDB. Many developers prefer PDO because the same approach works if the database later changes. Old mysql functions from early PHP versions have been removed and must not be used in new work.
Keep connection details such as host, user name and password outside your public web folder or in environment settings. Never place them in a file that can be downloaded, and never share them in public repositories.
PDO and MySQLi compared
| Feature | PDO | MySQLi |
|---|---|---|
| Databases supported | Several, through database-specific drivers | MySQL only |
| Interface style | Object oriented | Object oriented and procedural |
| Server-side prepared statements | Yes | Yes |
| Client-side prepared statements | Yes | No |
What is the CRUD cycle?
Most data features follow four actions, known as CRUD:
- Create: add a new record, such as a new customer.
- Read: fetch records to show them, such as a list of products.
- Update: change an existing record, such as a corrected address.
- Delete: remove a record, ideally after confirmation and permission checks.
Learning to build a small CRUD application is one of the best exercises for a beginner, because it combines forms, validation, SQL and page output in one project.
Why use prepared statements?
When a query includes values from the visitor, use prepared statements. The query is sent to the database with placeholders, and the values are supplied separately, so the database always treats them as data and never as part of the command. This is the standard protection against SQL injection and is explained again in the security guide on this site. Building queries by joining strings with user input is the habit to avoid.
Designing tables sensibly
Give every table a primary key that uniquely identifies each row. Use appropriate column types for numbers, dates and text. Use relationships between tables rather than repeating the same information: for instance, store customers once and link their orders by a customer identifier. Indexes make searches faster on columns that are often used for lookup, but each index has a cost when writing data, so add them thoughtfully.
When do you need a transaction?
Some operations involve several steps that must succeed or fail together, like reducing stock and recording an order. A transaction groups such steps. If any step fails, the database can roll everything back, which prevents half-finished data.
How do you display stored data safely?
When you show stored text on a page, escape it for HTML so that any special characters are displayed as text and not interpreted as markup. This prevents cross-site scripting. Also paginate long lists instead of loading everything at once, because large result sets slow the page and use memory.
File uploads in brief
Uploads need extra care. Check the size, check the type by examining the file and not only its name, give the stored file a new name generated by your code, and keep uploads in a location where they cannot be run as scripts. If you do not need uploads, do not offer them.
Handling errors
Database calls can fail because of a wrong query, a lost connection or a rule violation. Configure the database layer to report errors as exceptions, catch them where you can respond, and log the technical detail without showing it to visitors. A friendly message and a log entry serve both users and developers.
Practice project
Build a simple enquiry system. Create a form with name, email and message. Validate on the server, store the entry using a prepared statement, show a thank-you page, and create a protected page that lists the entries with pagination. Along the way you will use almost every idea in this guide.
Summary
Forms bring data in, validation checks it, prepared statements store it safely, and escaping shows it safely. Keep each step separate and careful, and your applications will be both useful and secure.
Sources and further reading
- PHP Manual: $_GET: defines $_GET as the variables passed through the URL query string.
- PHP Manual: $_POST: defines $_POST as variables passed by HTTP POST with form content types.
- PHP Manual: PDO: describes PDO as a data-access abstraction layer that does not rewrite SQL and needs a database-specific driver.
- PHP Manual: Choosing an API (MySQL): compares mysqli and PDO_MySQL, including OOP and procedural interfaces and server-side and client-side prepared statements.
- PHP Manual: PDO prepared statements and stored procedures: explains named and question-mark placeholders, repeated execution and that exclusive use of prepared statements prevents SQL injection through the bound values.
- PHP Manual: SQL Injection: recommends binding all data with prepared statements, notes that binding covers data only, and advises connecting with minimal-privilege database users.
- PHP Manual: htmlspecialchars: lists the characters converted to HTML entities and the default flags since PHP 8.1.
Frequently asked questions
What is the difference between GET and POST?
GET puts data in the address and suits searches, while POST sends data in the request body and suits actions that change something.
Should I use PDO or MySQLi?
Both are valid. PDO works with many database systems through one interface, while MySQLi is specific to MySQL and MariaDB.
Is browser-side validation enough?
No. Browser checks can be bypassed, so always validate again on the server.
What does CRUD mean?
CRUD stands for create, read, update and delete, the four basic actions performed on stored data.