我是 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++;
}
最佳答案
首先,请注意这一行:
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
如果任何数组元素的清理失败,将返回 FALSE。在您的代码中,您应该在清理后立即测试 if($input)。
此外,您需要进一步清理输入以避免 SQL 注入(inject)和 XSS 攻击。 (例如删除 SQL 转义字符和其他可注入(inject)字符)。
http://php.net/manual/en/mysqli.real-escape-string.php
最后,建议您使用绑定(bind)参数或完全净化的输入以避免 SQL 注入(inject)攻击。
关于javascript - 在 php 中解释 json 并将其传递给 mysql 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47698466/