php mysql_real_escape_string()函数

mysql_real_escape_string() 函数转义 SQL 语句中使用的字符串中的特殊字符,下列字符受影响:

x00 n r ' " x1a

如果成功,则该函数返回被转义的字符串,如果失败,则返回 false.

语法:mysql_real_escape_string(string,connection)

参数 描述

string 必需,规定要转义的字符串

connection 可选,规定 MySQL 连接,如果未规定,则使用上一个连接.

PHP实例代码如下:

  1. <?php
  2. function opendatabase ($host,$user,$pass) {
  3. try {
  4. if ($db = mysql_connect ($host,$user,$pass)){
  5. return $db;
  6. } else {
  7. throw new exception ("Sorry, could not connect to mysql.");
  8. }
  9. } catch (exception $e) {
  10. echo $e->getmessage ();
  11. }
  12. }
  13. function selectdb ($whichdb, $db){
  14. try {
  15. if (!mysql_select_db ($whichdb,$db)){
  16. throw new exception ("Sorry, database could not be opened.");
  17. }
  18. } catch (exception $e) {
  19. echo $e->getmessage();
  20. }
  21. }
  22. function closedatabase ($db){
  23. mysql_close ($db);
  24. }
  25. $db = opendatabase ("localhost","root","");
  26. selectdb ("mydatabase",$db);
  27. $_POST['user'] = "myname";
  28. $_POST['pass'] = "mypassword";
  29. function validatelogin ($user,$pass){
  30. mysql_real_escape_string ($user);
  31. mysql_real_escape_string ($pass);
  32. $thequery = "SELECT * FROM userlogin WHERE username='$user' AND password='$pass'";
  33. if ($aquery = mysql_query ($thequery)){
  34. if (mysql_num_rows ($aquery) > 0){
  35. return true;
  36. } else {
  37. return false;
  38. }
  39. } else {
  40. echo mysql_error();
  41. }//开源代码phpfensi.com
  42. }
  43. if (validatelogin ($_POST['user'],$_POST['pass'])){
  44. echo "You have successfully logged in.";
  45. } else {
  46. echo "Sorry, you have an incorrect username and/or password.";
  47. }
  48. closedatabase ($db);
  49. ?>