php - json函数将数据保存到数据库时出错

标签 php mysql json

我已经尝试了很多,但我一直无法找出这个将两个值保存到数据库的函数有什么问题。另一个函数保存一个值一直工作得很好。这里的行为很奇怪。有时发送“父”值,有时停止发送,但从不发送消息值。这里是函数。它对于一个输入(即父级)工作正常,但问题始于添加第二个输入。

<script> 
function ADDLISITEM(form)
{ 
var parent = form.txtInput.value;
    var msg    = form.msgInput.value;
    form.txtInput.value = "";
    form.msgInput.value = "";
    var url = "send_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
 }
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
    if (request.readyState == 4) {
        if (request.status == 200) {
            //alert('POST');
    } else {
        alert(request.status); // fails here
    }
    }
}
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + 
    encodeURIComponent(msg).replace(/%20/g, '+'));
}
</script>

这是send.php

$用户名 = "巴巴尔";
$密码 = "k4541616";
$主机名 = "本地主机";
$dbh = mysql_connect($主机名, $用户名, $密码) 或 die("无法连接
到 MySQL");
$selected = mysql_select_db("spec",$dbh) 或 die("无法选择first_test");

  //die(var_export($_POST,TRUE));

  $parent = $_POST['parent'];
  $msg = $_POST['msg'];
  $name   = 'Akhtar Nutt';
  //$parent2 = json_decode($parent);
  $msg_ID = '2q7b2sfwwe';
  //$msg2    = json_decode($msg);
  $query  =  "INSERT INTO msg2_Qualities(id,name,msg,msg_id,parent) VALUES  
  ('','$name','$msg','$msg_ID','$parent')";
    if(!mysql_query($query, $dbh))
        {die('error:' .mysql_error())
      ;}

?>

最佳答案

改变

request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));

至:

request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));

您的查询字符串中缺少参数分隔符 &...

您可能还希望避免使用 $_REQUEST 中的值,因为它们不可靠。如果您的脚本需要来自 POST 的数据,则从 $_POST 检索这些值。

关于php - json函数将数据保存到数据库时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4315474/

相关文章:

php - 在 PHP 中关闭大括号后的分号

PHP 登录表单 : SQL database Password

java - 为什么 JacksonJsonProvider 会忽略 MediaType 的参数?

Objective-C - 将项目从 NSDictionary 添加到 NSMutableDictionary

php mysqli异常,插入和读取数组

php - 如何获取 excel 单元格中存在的图像?

php - 如何实现一个可以轻松与SendGrid集成的邮件队列

php - 订购带有权重的数组?

mysql - SQL从每个组中获取最大值

python - Scrapy process.crawl() 导出数据到json