2013-11-03 145 views
3

来自人们对我以前的问题的建议似乎没有帮助。所以,我想这里完整的代码再次发布它的: mysql_depricated.php:Escape&in a string?

<script> 
function fun() 
{ 
var ajaxRequest; // The variable that makes Ajax possible! 

    try{ 
     // Opera 8.0+, Firefox, Safari 
     ajaxRequest = new XMLHttpRequest(); 
    } catch (e){ 
     // Internet Explorer Browsers 
     try{ 
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
     } catch (e) { 
      try{ 
       ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
      } catch (e){ 
       // Something went wrong 
       alert("Your browser broke!"); 
       return false; 
      } 
     } 
    } 

    var name = document.getElementById("name").value; 
    var url = "mysql_depricated2.php"; 
    var param = "name=" + name; 

    ajaxRequest.open("POST", url, true); 

//Send the proper header information along with the request 
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
ajaxRequest.setRequestHeader("Content-length", param.length); 
ajaxRequest.setRequestHeader("Connection", "close"); 

    ajaxRequest.send(param); 
} 
</script> 

<input type="text" id="name"> 
<input type="button" value="ajax&" onclick="fun()"> 

mysql_depricated2:

<?php 
     $host="localhost"; // Host name 
     $username="root"; // Mysql username 
     $password=""; // Mysql password 
     $db_name="example"; // Database name 

    // Connect to server and select databse. 
    $con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$db_name")or die("cannot select DB"); 


$content = $_POST['name']; 
$content=mysql_real_escape_string($content); 

$sql = "insert into e values('$content')"; 
mysql_query($sql); 
?> 

,如果我尝试插入含有&符号的字符串,不工作。请任何解决方案?

+1

重复您自己的问题:[&不能通过PHP插入MYSQL](http://stackoverflow.com/questions/19753471/cant-be-inserted-in-mysql-through-php)。如果你想提供进一步的信息,然后**编辑**现有的问题,不要再问它。 – Quentin

回答

4

替换您如下一行:

ajaxRequest.send(param); 

这一个:

ajaxRequest.send(encodeURIComponent(param)); 

所以你编码&特殊字符的URL编码形式是%26

+0

我应该怎么做才能解码,以便它可以成功插入数据库? @Nelson – rosemary

+0

你不需要做任何特殊的事情来解码它,PHP会自动为你做。 – Nelson

+0

如果我使用encodeURIComponent和echo $ content,它只显示一个空字符串 – rosemary