我正在尝试使用将所有对象插入我的数据库的循环解码json,以下是我的PHP代码,但我有错误:致命错误:无法在phptest中使用stdClass类型的对象作为数组。第21行的PHP
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
foreach($request as $key => $value) {
$equip = $value['equipment'];
$sql = "INSERT INTO contratos (equipo) VALUES ('$equip')";
}
}
我使用angular发布了json,下面的代码是我的controller.js
$scope.continue = function(choices)
{
var data = $scope.choices;
$http.post('php/phptest.php', data)
.then(function(response) {
console.log(response);
});
};
和json
[
{
"id":"choice1",
"quantity":1,
"equipment":"BLONG - F25",
"teamvox":true,
"plandatos":"D50"
},
{
"id":"choice2",
"quantity":1,
"equipment":"OUTERFONE - S17",
"evidence":true,
"mobictrl":true,
"plandatos":"D100"
}
]
答案 0 :(得分:1)
您尝试在foreach
循环中使用像数组一样的对象。但是json_decode
成了一个对象。您可以通过将true
传递给第二个参数来更改此行为。
$postdata = file_get_contents("php://input");
$request = json_decode($postdata, true);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
foreach($request as $key => $value) {
$equip = $value['equipment'];
$sql = "INSERT INTO contratos (equipo) VALUES ('$equip')";
}
}
答案 1 :(得分:1)
您可以使用$value->equipment
代替$value[equipment]
,因为返回的值不是数组而是stdClass对象。
答案 2 :(得分:1)
解决房间里的另一头大象; SQL注入漏洞
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// make MySQLi throw exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare('INSERT INTO `contratos` (`equipo`) VALUES (?)');
$stmt->bind_param('s', $equip);
foreach ($request as $data) {
$equip = $data->equipment; // $data is a stdclass
$stmt->execute();
}