-3

Possible Duplicate:
Best way to stop SQL Injection in PHP
How do I sanitize input with PDO?

I'm pulling in an id via $_GET. I just started using PDO and I'm unsure if this is safe or not. Obviously, the code below is using $_GET to grab an id. I'm not sanitizing it at all before I place it in the query. Is this safe?

<?php
if (isset($_GET['id'])) {
$blogid = $_GET['id'];
$post = $dbh->query("SELECT id, title, slug, body, image, author, date, category from   blog WHERE id='$blogid' ORDER BY date DESC");
$row = $post->fetch(); ?>
Community
  • 1
  • 1
Paul Dessert
  • 6,363
  • 8
  • 47
  • 74

2 Answers2

2

I'm not sanitizing it at all before I place it in the query

Nope. Not safe at all. :)

You either need to escape it, or use a prepared statement. With PDO, I would use a prepared statement:

if (isset($_GET['id']) && is_string($_GET['id'])) {
    $blogid = $_GET['id'];
    $stmt = $dbh->prepare("SELECT id, title, slug, body, image, author, date, category from   blog WHERE id= :id ORDER BY date DESC");
    $stmt->execute(array('id' => $_GET['id']));
    $row = $stmt->fetch();
}
Corbin
  • 33,060
  • 6
  • 68
  • 78
0

It is NEVER safe to insert a variable in a SQL query without sanitizing/escaping it.

What you could do, if you don't want to escape it yourself is to use a prepare statement and bind your parameters.

You can check the PHP documentation...

About of how use PDO prepare: http://php.net/manual/en/pdo.prepare.php

How to use the parameters binding: http://www.php.net/manual/en/pdostatement.bindparam.php

Maxime
  • 8,645
  • 5
  • 50
  • 53