我正在创建一个Android应用程序,并通过JSON将用户详细信息从Android应用程序提交到服务器端的php。但在服务器端,我没有得到JSON数据。在服务器端php,来自android应用程序的JSON似乎为null。我正在使用POST方法。我知道我的POST方法代码在服务器端的PHP中是错误的。但我不知道要解决这个问题。
这是我获取JSON的PHP代码。每次我收到相同的消息:
缺少必填字段
代码:
<?php
/*
* Following code will create a new user row
* All user details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
print_r($_POST);
// check for required fields
if (isset($_POST['Firstname']) && isset($_POST['Lastname']) && isset($_POST['Username']) && isset($_POST['Email']) && isset($_POST['Password']) && isset($_POST['Country']) && isset($_POST['Mobile'])) {
echo('bhargavi');
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Username = $_POST['Username'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$Country = $_POST['Country'];
$Mobile = $_POST['Mobile'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO users(Firstname,Lastname,Username,Email,Password,Country,Mobile) VALUES('$Firstname','$Lastname','$Username','$Email','$Password','$Country','$Mobile')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully Registered.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
答案 0 :(得分:0)
在检查$ _POST [&#39;名字&#39;]等之前,你应该解码json字符串......
我们假设您从应用程序发送一个名为data的字符串。在PHP上你应该做这样的事情:
$data = json_decode($_POST['data']);
and then check if $data contains the data you neeed by doing:
if (isset($data->Firstname) && isset($data->Lastname) etc...){
...
...
}
如果我可以给你一个建议,如果你直接从你的应用程序检查数据完整性而不是在你的服务器上执行它会更好,它将有机会节省一些服务器资源......
正如Jay Blanchard已经提到的那样,不要使用mysql,否则你将接触到mysql注入......