As PHP is one of the most loved languages among web developers, there are many popular websites and web applications built with PHP. Your code needs to be secure in order to defend against various vulnerabilities and attacks. One of the most popular attack is SQL Injection, All poorly coded websites are vulnerable to SQL Injection attack. Using prepared statements to execute SQL query is the best way to overcome the problem of SQL Injection in your web app.
Coding a registration page in PHP is not a big deal but making it secure and robust is not easy. Let’s see how we can use PDO for database connectivity and use prepared statements to get rid of SQL Injection attack and making our web app secure. In this tutorial we will code a simple registration page to take input from user and submit the data into database securely. There are various other advantages of using PDO which are as follows:
- With PDO, you can write database access code that isn’t tied to any specific database, it means if in future you want to change your database then you need to change the respective database driver only.
- Its included in core PHP 5.3 and later version.
Note: Make sure you have un-commented dll files of pdo in PHP.INI file. Open your ‘PHP.INI‘ file and look for extension=php_pdo_mysql.dll. Remove comment symbol as shown below:
Let’s start with the database design. For this simple tutorial let’s create a simple table named “registered”.
SQL query to create table:
CREATE TABLE IF NOT EXISTS <code>registered</code> ( <code>id</code> int(10) NOT NULL AUTO_INCREMENT, <code>Name</code> varchar(20) NOT NULL, <code>Email</code> varchar(20) NOT NULL, <code>Password</code> varchar(20) NOT NULL, PRIMARY KEY (<code>id</code>) )
Code for index.html:
<HTML> <head> <title>Simple Registration Page To Use PDO</title> </head> <body> <form action="register.php" method="post"> <label> Enter Your Name</label><input type="text" name="fname" id="fname"></input> <br> <label> Enter Your Email</label> <input type="email" name="email" id="email"></input> <br> <label> Enter Password </label> <input type="password" name="pwd" id="pwd"></input> <input type="submit" value="Register" /> </form> </body> </html>
Code For Register.php:
<?php $dbh = new PDO('mysql:host=localhost;dbname=register', 'root', '12345'); $stmt = $dbh->prepare("insert into registered(name, email, password) values (?,?,?)"); $stmt->bindParam(1, $name); $stmt->bindParam(2, $email); $stmt->bindParam(3, $pwd); $name = $_POST["fname"]; $email = $_POST["email"]; $pwd = $_POST["pwd"]; $stmt->execute(); echo "<p>Thank you for registering!</p>"; ?>
This tutorial is just to show how you can use PDO for database connectivity and use prepared statements to execute SQL queries. You can create a fully functional registration page by adding appropriate checks and validations.