有问题在php中解释json并将其传递给mysql

时间:2017-12-07 15:30:17

标签: javascript php mysql json

我是php新手,我不知道如何调试它。

我正在尝试将json传递到php页面,然后将该数据发送到mySQL。

我认为解决php文件中的数据或将信息传递到php页面时遇到问题。当我打开php文件时,它会显示它正在正确访问数据库。

这是我的javascript代码:

 var request = new XMLHttpRequest();
                  request.open('POST', 'http://website/saveF.php', true);
                  request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
                  request.send(bInfo);

这将获取信息并将其传递给php文件,然后将其添加到mySQL数据库中。

这是我的php代码:

这是解码jSon然后迭代数组内的每个条目。然后询问是否列出了网站,并将其存储在相应的表格中。

//as long as the connection is good then we keep it live.
include_once "head.php";

if ($conn->connect_error) {
    die("connection failed: " . $conn->connect_error);
}

//gettting the information from the front end (index.html)
$inputJSON = file_get_contents('php://input');
//decode all the previously encoded information
$postThings = json_decode($inputJSON, TRUE);
$input = filter_var($postThings, FILTER_SANITIZE_STRING); 

//create a variable the is the total length of our array
$totalNum = count($input);
//arrays start at 0
$i = 0;
//you can see where this is going. We have a while loop that will continue as long as i is less than totalnum. Ask me why i didn't use a for loop.... I don't have an answer.

    while($i < $totalNum){
        $var0 = $input[$i][0]; 
        $var1 = $input[$i][1]; 
        $var2 = $input[$i][2];
        $var3 = $input[$i][3];
        $var4 = $input[$i][4];
        $var5 = $input[$i][5];
        $var6 = $input[$i][6];

        if($var1 == "Not Listed") {
            $sql = "INSERT INTO missing(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
        }else{

            //here we set the information into the database.
           $sql = "INSERT INTO companies(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
    }


        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

        $i++;
    }

1 个答案:

答案 0 :(得分:0)

首先,请注意这一行:

$input = filter_var($postThings, FILTER_SANITIZE_STRING);

如果对任何数组元素进行清理失败,则返回FALSE。在您的代码中,您应该在清理后立即测试if($ input)。

此外,您还需要进一步清理输入以避免SQL注入和XSS攻击。 (例如,删除SQL转义字符和其他可注入字符)。

http://php.net/manual/en/mysqli.real-escape-string.php

最后,建议您使用绑定参数或完全清理的输入来避免SQL注入攻击。