5

As the title says: is this code safe enough from SQL injection?

Is there a better way to prevent SQL injection?

<?php
$hostname   = "xxx";
$username   = "xxx";
$dbname     = "xxx";

$password   = "xxx";
$usertable  = "xxx";
$yourfield  = "xxx";

$db = new PDO('mysql:host='.$hostname.';dbname='.$dbname.'', $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$query = $db->prepare("INSERT INTO `$usertable` (first_name, last_name, username) VALUES (:first_name, :last_name, :username)");
$query->bindValue(':first_name', $_POST['first_name']);
$query->bindValue(':last_name',  $_POST['last_name']);
$query->bindValue(':username',   $_POST['username']);

$query->execute();
?>
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
user2204292
  • 181
  • 1
  • 4
  • 10
  • 2
    The question is more suitable for [Code Review SE](http://codereview.stackexchange.com/about). Code Review is a question and answer site for sharing code from projects you are working on for peer review. – hjpotter92 Mar 24 '13 at 10:57

3 Answers3

5

If you use only prepare statments as in your code above you are secure. There are AFIK no other posibilities to hack your site with SQL injections.

The prepare statments encupulates the data from the commands so can no content be executed as part of a SQL statment.

rekire
  • 47,260
  • 30
  • 167
  • 264
1

Yes, prepared queries are generally near-100% safe from SQL Injections. However, I would recommend also passing in the data_type argument to PDO::bindParam();

See: Are Prepared Queries 100% Safe Against SQL Injections

Community
  • 1
  • 1
Tushar
  • 8,019
  • 31
  • 38
1

Yes this PDO code safe enough from SQL injection.

Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100