Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

php - Whats does pg_escape_string exactly do?

I'm using the following script which takes the data from a html form and stores in a Postgres DB. There is this pg_escape_string function which stores the value from the form to the php variable. Searching the web throughout, I found that pg_escape_string escapes a string for insertion into the database. I'm not much clear on this. What does it actually escaping? What actually happens when its said that a string is 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Consider the following code:

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

Now suppose that $name is "Chicago O'Hare". When you do the string interpolation, you get this SQL code:

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

which is ill-formed, because the apostrophe is interpreted as a SQL quote mark, and your query will error.

Worse things can happen, too. In fact, SQL injection was ranked #1 Most Dangerous Software Error of 2011 by MITRE.

But you should never be creating SQL queries using string interpolation anyway. Use queries with parameters instead.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...