日期:2014-05-17  浏览次数:20518 次

一段网页脚本插入到mysql数据库的问题?
JScript code

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-22266712-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? '  https://ssl' : '  http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>


这样整个一段脚本插入到mysql中,提示错误:
You have an error in your sql syntax: check the manual that corresponds to Your MySql server version for the right syntax to use near ' desc, keyward title values('<script type="text/javascript">)
var _gaq = ' at line 1

这个问题改怎么解决?

------解决方案--------------------
插入代码是怎样的,字符串是在文件里,还是直接在cs文件里写的?
------解决方案--------------------
插入的时候生成的SQL 有语法错误 是<script type="text/javascript">这些标签的问题

插入的时候要把HTML特殊标签替换掉

C# code
 /// <summary>
        /// 插入SQL时替换字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Encode(string str)
        {
            str = str.Replace("'", "''");
            str = str.Replace("\"", "&quot;");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("\n", "<br>");
            str = str.Replace("“", "&ldquo;");
            str = str.Replace("”", "&rdquo;");
            return str;
        }

        /// <summary>
        /// 取SQL值时还原字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Decode(string str)
        {
            str = str.Replace("&rdquo;", "”");
            str = str.Replace("&ldquo;", "“");
            str = str.Replace("<br>", "\n");
            str = str.Replace("&gt;", ">");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&quot;", "\"");
            str = str.Replace("''", "'");
            return str;
        }

------解决方案--------------------
脚本入库前处理一下:htmlspecialchars
------解决方案--------------------
探讨

刚试过了,以上的代码如果转义后就可以请看
SQL code
insert into test1(title,counts) values('aaa','<script type=\"text/javascript\">
var _gaq = _gaq || [];
_gaq.push([\'_setAccount\', \'UA-22581801-1\']);
_gaq.push……

------解决方案--------------------
是不是转义符造成的?

php.ini文件里的magic_quotes_gpc设成了off,那么PHP就不会在敏感字符前加上反斜杠(\)