mysql escape 函数_函数mysql_real_escape_string的使用详解

[导读]mysql_real_escape_string函数转义SQL语句中使用的字符串中的特殊字符。

php mysql_real_escape_string() 函数定义和用法

mysql_real_escape_string() 函数转义 sql 语句中使用的字符串中的特殊字符。

下列字符受影响:

x00

"

x1a

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

语法mysql_real_escape_string(string,connection)

参数描述string必需。规定要转义的字符串。connection可选。规定 mysql 连接。如果未规定,则使用上一个连接。

说明

本函数将 string 中的特殊字符转义,并考虑到连接的当前字符集,因此可以安全用于 mysql_query()。

提示和注释

提示:可使用本函数来预防数据库攻击。

例子例子 1<?php $con = mysql_connect("localhost", "hello", "321");if (!$con)  {  die(could not connect:  . mysql_error());  }// 获得用户名和密码的代码// 转义用户名和密码,以便在 sql 中使用$user = mysql_real_escape_string($user);$pwd = mysql_real_escape_string($pwd);$sql = "select * from users whereuser=" . $user . " and password=" . $pwd . ""// 更多代码mysql_close($con);?>

例子 2

数据库攻击。本例演示如果我们不对用户名和密码应用 mysql_real_escape_string() 函数会发生什么:<?php $con = mysql_connect("localhost", "hello", "321");if (!$con)  {  die(could not connect:  . mysql_error());  }$sql = "select * from userswhere user={$_post[user]}and password={$_post[pwd]}";mysql_query($sql);// 不检查用户名和密码// 可以是用户输入的任何内容,比如:$_post[user] = john;$_post[pwd] = " or =";// 一些代码...mysql_close($con);?>

那么 sql 查询会成为这样:select * from userswhere user=john and password= or =

这意味着任何用户无需输入合法的密码即可登陆。

例子 3

预防数据库攻击的正确做法:<?phpfunction  check_input($value){// 去除斜杠if (get_magic_quotes_gpc())  {  $value = stripslashes($value);  }// 如果不是数字则加引号if (!is_numeric($value))  {  $value = "" . mysql_real_escape_string($value) . "";  }return $value;}$con = mysql_connect("localhost", "hello", "321");if (!$con)  {  die(could not connect:  . mysql_error());  }// 进行安全的 sql$user = check_input($_post[user]);$pwd = check_input($_post[pwd]);$sql = "select * from users whereuser=$user and password=$pwd";mysql_query($sql);mysql_close($con);?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值