MySQL/PHP:允许特殊字符并避免 SQL 注入 [英] MySQL/PHP: Allow special characters and avoid SQL injection

查看:75
本文介绍了MySQL/PHP:允许特殊字符并避免 SQL 注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何允许特殊字符如 " ' \/: ; 等而不使用以下代码打开 SQL 注入:

How can I allow special characters like " ' \ / : ; etc without open up for SQL injection using the code below:

$opendb = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

$text = $_POST['text'];

mysql_query("UPDATE table SET text='" . $text . "' WHERE 
id='" . $_GET['id'] . "'");

mysql_close($opendb);

$text 包含来自 HTML 文本区域的句子.当我尝试在引号中输入文本时,它只是在引号之前插入文本.

$text contains a sentence from a HTML textarea. When I tries to enter text in a quote it just insert the text before the quotes.

推荐答案

好吧,也许最简单的解决方案是使用 mysql_real_escape_string() 函数,如下所示:

Well, maybe the simplest solution is to use mysql_real_escape_string() function like this:

$opendb = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

$text = $_POST['text'];

mysql_query("UPDATE table SET text='" . mysql_real_escape_string($text) . "' WHERE 
id='" . $_GET['id'] . "'");

mysql_close($opendb);

使用此代码,您可以将 $text 变量中的特殊字符保存到数据库中.

using this code you could allow special characters in $text variable to be saved into the database.

你也应该转义 $_GET['id'].

You should escape $_GET['id'] also.

这篇关于MySQL/PHP:允许特殊字符并避免 SQL 注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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