Jump to content

pdo and sql injections


Dragen

Recommended Posts

Am I right in thinking that data input into a mysql database using pdo is safe from sql injections?

I read on the pdo page:

The user input is automatically quoted, so there is no risk of a SQL injection attack.

 

Is this always the case with pdo, or is it just for certain methods of database input?

for example, if I had my query as this:

$dbh->query("INSERT INTO `table` ('var') VALUES ($variable)"

would I need to do anything to safeguard from sql injections?

Link to comment
Share on other sites

Good point. So is this a good way of doing it?

		try{
		$stmt = $dbh->prepare("SELECT `name` FROM `users` WHERE `id` = '?' LIMIT 1");
			if($stmt->execute(array($id))){
				while($row = $stmt->fetch()){
					return $row['name'];
				}
			}else{
				return false;
			}
	}catch(PDOException $e){
	   return false;
	}		

I did try without the try/catch part, but on an sql error it throws up a whole error, whereas I was hoping the if/else statement would stop that. Reading up on pdo though it seems that it throws out all errors as a safety feature.

Link to comment
Share on other sites

Exceptions are becoming more prevalent in PHP now, and my suggestion is to use them as they can be handy ;)

In your catch statement you can use

...} catch (PDOException $e) {
  // Log error to log file using $e->getMessage();
  // or mail me the SQL statement + pdo error message.
}

 

Unfortunately there's not a lot you can do stop PDO throwing an exception (unless you extend it and override the function, but we're not going there).

Link to comment
Share on other sites

Good point. So is this a good way of doing it?

 

Yes, except it should be

$stmt = $dbh->prepare("SELECT `name` FROM `users` WHERE `id` = ? LIMIT 1");

(without the single quotes around the question mark) as PDO will handle that for you. Otherwise you might end up with two single quotes.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.