Sto usando il seguente script che prende i dati da un modulo html e li archivia in un DB Postgres. Esiste questa funzione pg_escape_string che memorizza il valore dal modulo alla variabile php. Cercando in tutto il web, ho trovato che pg_escape_string sfugge a una stringa per l'inserimento nel database. Non sono molto chiaro su questo. Cosa sfugge davvero? Cosa succede realmente quando dice che una stringa è sfuggita?Che cosa fa esattamente pg_escape_string?
<html>
<head></head>
<body>
<?php
if ($_POST['submit']) {
// attempt a connection
$dbh = pg_connect("host=localhost dbname=test user=postgres");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// escape strings in input data
$code = pg_escape_string($_POST['ccode']);
$name = pg_escape_string($_POST['cname']);
// execute query
$sql = "INSERT INTO Countries (CountryID, CountryName) VALUES('$code', '$name')";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Country code: <br> <input type="text" name="ccode" size="2">
<p>
Country name: <br> <input type="text" name="cname">
<p>
<input type="submit" name="submit">
</form>
</body>
</html>
Questo è davvero vecchio, ma per chi lo incontra più tardi, pg_escape_string() è una difesa contro l'iniezione SQL, ma non lo impedisce. Usare le dichiarazioni preparate è meglio. (http://stackoverflow.com/questions/732561/why-is-using-a-mysql-prepared-statement-more-secure-than-using-the-common-escape) – pandubear