【发布时间】:2017-12-07 15:30:17
【问题描述】:
我是 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++;
}
【问题讨论】:
-
你为什么不用
$_POST数组? -
您的代码容易受到SQL injection 攻击。您应该通过mysqli 或PDO 驱动程序使用带有绑定参数的准备好的语句。 This post 有一些很好的例子。
-
@Luca 我没有使用 $_POST 数组,因为无论我从哪里学到的都没有。我意识到我应该,但现在 tphp://input 正在工作。
-
我也意识到我需要使用准备好的语句,但代码不能正常工作,所以我需要先解决这个问题。
-
你的 json 是什么样的?它只是一个数组吗?依赖数组中值按特定顺序排列的数据就像自找麻烦。
标签: javascript php mysql json