What does pg_escape_string do?

I use the following script that takes data from an html form and stores it in Postgres DB. There is a function pg_escape_string that saves the value from the form to the php variable. Searching the Internet for everything, I found that pg_escape_string escapes a string to insert into the database. I do not really understand this. What is it really slipping away? What actually happens when a line is said to have escaped?

<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> 
+6
source share
2 answers

Consider the following code:

 $sql = "INSERT INTO airports (name) VALUES ('$name')"; 

Suppose now that $name "Chicago O'Hare" . When you interpolate strings, you get this SQL code:

 INSERT INTO airports (name) VALUES ('Chicago O'Hare') 

which is poorly formed because the apostrophe is interpreted as an SQL quotation mark, and your request will be erroneous.

Worse things can also happen . In fact, SQL injection was ranked # 1 The Most Dangerous Software Error of 2011 from MITER.

But you should never create SQL queries using string interpolation. Use query with parameters instead.

 $sql = 'INSERT INTO airports (name) VALUES ($1)'; $result = pg_query_params($db, $sql, array("Chicago O'Hare")); 
+5
source

pg_escape_string () prevent sql injection in your code

+1
source

Source: https://habr.com/ru/post/896375/


All Articles