如何在PHP中使用mysql_real_escape_string函数 [英] How to use mysql_real_escape_string function in PHP

查看:63
本文介绍了如何在PHP中使用mysql_real_escape_string函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在我正在编写的此程序中,我实际上是使用表单从用户那里获取SQL查询.然后,我继续在数据库上运行该查询.

So in this program I'm writing, I actually grab a SQL query from the user using a form. I then go on to run that query on my database.

我知道不要信任"用户输入,因此我想对输入进行清理.我正在尝试使用mysql_real_escape_string,但未能成功使用它.

I know not to "trust" user input, so I want to do sanitization on the input. I'm trying to use mysql_real_escape_string but have been unsuccessful in getting it to work.

鉴于输入,这是我正在尝试的内容: select * from Actor;

Here's what I'm trying, given the input: select * from Actor;

//"query" is the input string: 
$clean_string = mysql_real_escape_string($query, $db_connection); 
$rs = mysql_query($clean_string, $db_connection); 
if (!$rs) 
{ 
    echo "Invalid input!"; 
} 

这总是给我

输入无效!"

"Invalid input!"

错误.

当我取出clean_string部分并仅对查询运行mysql_query时,

When I take out the clean_string part and just run mysql_query on query, the

"无效 输入"

"invalid input"

消息不输出.相反,当我这样做时:

message is not output. Rather, when I do this:

$rs = mysql_query($query, $db_connection); 
if (!$rs) 
{ 
   echo "Invalid input!"; 
} 

它不输出

无效输入".

"invalid input".

但是,我需要使用mysql_real_escape_string函数.我在做什么错了?

However, I need to use the mysql_real_escape_string function. What am I doing wrong?

更新:

给出 select * from Actor;作为输入,我发现了以下内容.

Given select * from Actor; as an input, I've found the following.

使用我已经使用过的echo语句 发现在清除之前,该字符串包含以下值: select * from Actor; 哪个是正确的.但是,经过消毒后,它不正确 值select *\r\nfrom Actor;,因此出现错误消息.为什么是 mysql_real_escape_string这样做吗?

Using echo statements I've found that before sanitizing, the string holds the value: select * from Actor; which is correct. However, after sanitizing it holds the incorrect value of select *\r\nfrom Actor;, hence the error message. Why is mysql_real_escape_string doing this?

推荐答案

将其用于查询中的实际值,而不是整个查询字符串本身.

use it on the actual values in your query, not the whole query string itself.

示例:

$username = mysql_real_escape_string($_POST['username']);
$query = "update table set username='$username' ...";
$rs = mysql_query($query);

这篇关于如何在PHP中使用mysql_real_escape_string函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆