How To Quote Text Values in SQL Statements?

Text values in SQL statements should be quoted with single quotes ('). If the text value contains a single quote ('), it should be protected by replacing it with two single quotes (''). In SQL language syntax, two single quotes represents one single quote in string literals. The tutorial exercise below shows you two INSERT statements. The first one will fail, because it has an un-protected single quote. The second one will be ok, because a str_replace() is used to replace (') with (''):

  include "mysql_connection.php";
  $notes = "It's a search engine!";
  $sql = "INSERT INTO fyi_links (id, url, notes) VALUES ("
      . " 201, 'www.google.com', '".$notes."')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }

  $notes = "It's another search engine!";
  $notes = str_replace("'", "''", $notes);
  $sql = "INSERT INTO fyi_links (id, url, notes) VALUES ("
      . " 202, 'www.yahoo.com', '".$notes."')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
  mysql_close($con);
?>
If you run this script, you will get something like this:
SQL statement failed.
1 rows inserted.

No comments:

Post a Comment

Mayur Raiyani