Already many days I'm documenting about the SQL Injection. I was wondering if the code I wrote is vulnerable in some of its parts.

if($_POST['nameone'] AND $_POST['nametwo'])
   $conn = new PDO("mysql:host=localhost;dbname=dbname;charset=utf8", 'dbuser', 'dbpass');
   mysql_query('SET NAMES utf8');
   $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
   $stmt = $conn->prepare("INSERT INTO `test_PDO`(`nameone`, `nametwo`) VALUES (:nomeone,:nometwo)");
   $nameone = $_POST['nameone'];
   $nametwo = $_POST['nametwo'];
   $stmt->bindParam(':nomeone', $nameone);
   $stmt->bindParam(':nometwo', $nametwo);
   echo "New records created successfully $nameone -- $nametwo";
   $conn = null;

<form method="POST">
  Name one: <input type="text" name="nameone"><br>
  Name two: <input type="text" name="nametwo"><br>
  <input type="submit">

It would be great if somebody could review and confirm that this code is indeed not vulnerable to SQL injection. Or if it is vulnerable, kindly point out where, and how to make it better.


1 Answer 1


No, it's not vulnerable to SQL Injection, as you use prepared statements, and you use them correctly.

If you don't have any CSRF protection it is however vulnerable to XSS because of the echo (and of course CSRF), but I'm assuming that that's more of a debug statements.


  • You don't really need the variables nameone and nametwo. One-time variables are only useful if you need to give them some name to increase readability.
  • You shouldn't use mysql_*. So if you want to set the character set you should use PDO (you can also pass it as optional MYSQL_ATTR_INIT_COMMAND parameter when initializing the connection, see eg here).
  • try to be consistent with your names (nome vs name).
  • use camelCase to make your names easier to read (nameone -> nameOne).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.