Yes you can do it. Parameterized queries are simple and it force you to define the SQL query beforehand, and use placeholders for the user-provided variables within the query. You can then pass in each parameter to the query after the SQL statement is defined, allowing the database to be able to distinguish between the SQL command and data inputted by a user. If SQL commands are inputted by an attacker, the parameterized query would treat these as untrusted input, and the injected SQL commands will never get to execute. Watch out the example provided below for more understanding.
if (isset($_GET['id'])){
$id = $_GET['id'];
/**
* Validate data before it enters the database. In this case, we need to check that
* the value of the 'id' GET parameter is numeric
*/
if ( is_numeric($id) == true){
try{
$dbh = new PDO('mysql:host=localhost;dbname=sql_injection_example', 'dbuser', 'dbpasswd');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/**
* Before executing our SQL statement, we need to prepare it by 'binding' parameters.
* We will bind our validated user input (in this case, it's the value of $id) to our
* SQL statement before sending it to the database server.
*
* This fixes the SQL injection vulnerability.
*/
$q = "SELECT username
FROM users
WHERE id = :id";
// Prepare the SQL query
$sth = $dbh->prepare($q);
// Bind parameters to statement variables
$sth->bindParam(':id', $id);
// Execute statement
$sth->execute();
$sth->setFetchMode(PDO::FETCH_ASSOC);
// Fetch result
$result = $sth->fetchColumn();
/**
* HTML encode our result using htmlentities() to prevent stored XSS and print the
* result to the page
*/
print( htmlentities($result) );
$dbh = null;
}
catch(PDOException $e){
/**
* You can log PDO exceptions to PHP's system logger, using the Operating System's
* system logging mechanism
*
* For more logging options visit http://php.net/manual/en/function.error-log.php
*/
error_log('PDOException - ' . $e->getMessage(), 0);
/**
* Stop executing, return an 'Internal Server Error' HTTP status code (500),
* and display an error
*/
http_response_code(500);
die('Error establishing connection with database');
}
} else{
/**
* If the value of the 'id' GET parameter is not numeric, stop executing, return
* a 'Bad request' HTTP status code (400), and display an error
*/
http_response_code(400);
die('Error processing bad or malformed request');
}
}
?>