微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用JSON插入时出现问题

我试图插入这样的数据

function submitData() {
//Posting to ContactDB with JSON format
$.post("contactDB.PHP",
    JSON.stringify({ 
          name: $("#name").val(),
          email: $("#email").val(),
          phone: $("#phone").val(),
          message: $("#message").val() 
    }),
    function(usrava){
        // if data is inserted successfully than show insert success message in Result div
        if(usrava=='Data Inserted')
        {
            $("#result").fadeto(200,0.1,function(){ 
                $(this).html('Your message is successfully saved with us. We will get back to you soon.').fadeto(900,1);
            });     
        }
        //else show the error 
        else
        {
            $("#result").fadeto(200,0.1,function(){ 
                $(this).html(usrava).fadeto(900,1);
            });
        }
    });
}   

ContactDB.PHP

<?PHP
    $MysqLi = new MysqLi("localhost", "root", "", "contactDB"); //Connection to the Database
    //If Error than die
    if (MysqLi_connect_errno()) { 
        die('Connect Error (' . MysqLi_connect_errno() . ') '. MysqLi_connect_error());
        //Echo for the response 
        echo "Data base connection NOT Successful. Please get the assistance from your Administrator.";
        //Should not go out if not connected
        exit();
    }
    //data received in json. decoded it to an array
    $data = json_decode(file_get_contents('PHP://input'), true);
    //Create a insert Command using implode as the data is already in the array
    $insert = "INSERT INTO contact(Name,Email,Phone,Message) VALUES ('" .implode(",",$data)."')";
    $MysqLi->query($insert);
    //Close the connection
    $MysqLi->close();
    // Echo for the response
    echo "Data Inserted";
?>

问题是我在$MysqLi->查询($insert)上遇到错误;你的sql语法有错误;查看与您的MysqL服务器版本相对应的手册,以便在Rajesh附近的第1行使用正确的语法

我应该怎么做才能让它运行.我已经尝试了一切,但找不到任何有效的解决方案.请帮忙!!提前致谢

解决方法:

函数implode将使用字符串连接数组元素.现在你的函数是implode(“,”,$data),它将使字符串像这样

NameData,EmailData,PhoneData,MessageData 

而你会希望这样做

'NameData','EmailData','PhoneData','MessageData'

所以要做到这一点,你需要使你的内爆函数看起来像这个implode(“’,’”,$data),并且第一个和最后一个已经从你编写的代码中进入.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐