PHP Form Handling
PHPSelecting Details with MySQLi
For instance you want to select all users from database:
When you don't know how to import this script to make the table, here's how: in MySQL, create a database. After that, go to the "SQL" tab, paste the table in the white placeholder and click "Go". Now you have a created an user and you can run the code to see what happens - does it display the user's username?
Connecting Database with MySQLi
Using the "MySQLi" system method, here's how to connect your database to web application:
This way you can create the MySQL database connection.
Connecting Database with PDO
Nowadays "PDO" is a method used more by modern websites, because its more secure and robust (prepared statements):
As mentioned, PDO uses prepared statements - that prevents SQL attacks, like injecting characters into database, affecting everything there.
CRUD (Create, Read, Update, Delete) with MySQLi
This way you have built a base for the CRUD system.
CRUD (Create, Read, Update, Delete) with PDO
Instance of the 'CRUD' system using PDO:
Using PDO to make the CRUD system takes much less code than MySQLi
Fetching Multiple Rows
To fetch all usernames and IDs from database for instance:
If you are starting out with PHP, learn the MySQLi method first - it basically teaches the structure of this language - PDO has just more a steeper learning courve to remember all of the words and extra signs.
Transactions
Making a transaction system into your website needs to have securities, here are examples:
Both are secure enough, but PDO is a better choice for this system.
Error Handling
Here are examples of using MySQLi and PDO with error handling:
Typically when using PDO, you have to put something into the first block in "try{}", since it starts looking into what you are building there.
Prepared Statements
Prepared statements are for user input escaping and SQL injection preventing. Here is an instance of inserting a new user into database:
MySQLi method uses the question mark "?" system that doesn't instantly insert the strings into database, instead there is the "bind paramater" method before that aswell, that makes sure they are both strings - so if an user were to insert a script or something malicious, the filter wouldn't validate that. PDO is the same - checks if the name and email are strings.
Closing Connection
This is important to use - it prevents the system running after a query (send request to database) is done:
This is a feature, which is highly recommended to use in your queries overall.