Kaka
Kaka

Reputation: 395

Translating my site to PDO, is this right?

I just recently started looking into pdo since I've been sticking with mysql for way too long. Right now I'm working on translating some scripts to PDO.

Is this completely safe from injection?

$name = isset($_GET['name']) ? $_GET['name'] : null;

$stmt = $db->prepare("SELECT id,name FROM users WHERE name = '$name'");
$stmt->execute();
$row = $stmt->fetch();



$stmt = $db->query("SELECT *, tr.name, t.name AS teamName FROM player AS p 
                LEFT JOIN team_ranks AS tr ON tr.id = p.rank_id 
                LEFT JOIN teams AS t on t.id = tr.team_id
                WHERE p.id = {$row['id']}");
$row = $stmt->fetch();

Upvotes: 1

Views: 43

Answers (1)

IMSoP
IMSoP

Reputation: 97968

Short answer: no. You've misunderstood prepared statements.

This line is still just creating a static SQL string using PHP double-quote expansion. PDO/MySQL doesn't get to know where your variable is, so can't protect you against injection.

$stmt = $db->prepare("SELECT id,name FROM users WHERE name = '$name'");

What you need to do is this:

$stmt = $db->prepare("SELECT id,name FROM users WHERE name = :name");

Here, :name is a placeholder passed to the database saying "there will be a variable here when this statement is actually run". Then to execute it, you pass a value for that placeholder, like passing an argument to a function:

$stmt->execute(array(':name' => $name));

Alternatively, you can use bindParam() to give PDO more information about the parameter:

$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();

The database now knows that the variable passed in should be treated as one string, not interpreted as SQL, so there is no way for code to be injected into the query.

Upvotes: 6

Related Questions