PDO


#1

I need sanitize this part of code. I have - SQL injection proteciotn is done , but I have no idea how and where to add sanitization

[php] if(isset($_POST[‘submit’])){

 try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO subskrypcja (imie,  email) VALUES (:imie, :email)");
$stmt->bindParam(':imie', $imie);
$stmt->bindParam(':email', $email);


$stmt->bindParam(':imie', $_POST['imie']);
    $stmt->bindParam(':email', $_POST['email']);

$stmt->execute();


echo "New records created successfully";
     header('Location:subskrypcja.php');
}

catch(PDOException $e)
{
echo "Error: ";
}
$conn = null;
}

  }[/php]

#2

Why are you adding sanitation?


#3

to protect my code from tags :slight_smile:


#4

some bastard tried to add javascript: alert(document.cookie) into my website( its not the first time. in the begining I had real_escape, but then I have been told to use PDO for SQL injection so I’m changing some code to PDO


#5

Then you want to encode the output. Sanitizing inputs does nothing when it is displayed to the page.


#6

ok, why I shouldn’t protect input? when I INSERTING data into DB?


#7

You are talking about two separate things.

Prepared [Parameterized] Statement protect the database.
html encoding protects the site.

So, a parameterized statement protects from,

[php]$_POST[‘name’] = "’); DELETE FROM User; – ";
$sql = “INSERT INTO User (name) VALUES (’” . $_POST[‘name’] . “’)”;[/php]

encoding prevents this,
[php]$_POST[‘name’] = “”;
$sql = “INSERT INTO User (name) VALUES (’” . $_POST[‘name’] . “’)”;
echo $_POST[‘name’];
[/php]


#8

is this correct way to do this. I have done this after adding this post. is this code protect me from sql injection and html tag?

[php]if(isset($_POST[‘submit’])){

 $stmt = $connection->prepare("INSERT INTO blabla(imie, email, hosting) VALUES (?, ?, ?)");

$stmt->bind_param(“sss”, $imie, $email, $ip);

// set parameters and execute
$imie = filter_var($_POST[‘imie’], FILTER_SANITIZE_STRING);
$email = filter_var($_POST[‘email’], FILTER_SANITIZE_STRING);
$ip=$_SERVER[“REMOTE_ADDR”];
$stmt->execute();
header(‘Location:subskrypcja.php’);
$stmt->close();
$connection->close();

           }[/php]

#9

If you are worried about the output, which it appears to be an issue, write a static class for it. One company did,

[php]class P
{
public static function rint($str) {
echo htmlentities($str);
}

}[/php]

So, when you call it, it was:

[php]P::rint(“”);[/php]


#10

I have found ( see this example above) and its working fine for me you are not able to add any html tags and I’m protected from sql injection. Thank you so much for help. cheers