在Android应用程序的PHP文件上发布JSON文件,并在PHP上将JSON解码为本地变量

时间:2022-10-17 09:30:12

I have been researching this for a while now and not getting anywhere.

我已经研究了一段时间而且没有到达任何地方。

What I'm trying to do is to create a registrion/login activities, which will store all access details on a remote SQL database.

我要做的是创建一个registrion / login活动,它将所有访问详细信息存储在远程SQL数据库中。

My outline of the code was to create the "Registrar" object, convert it to JSON object, and convert that JSON object to a string, and then send that string over httpclient as a post to the PHP page ( which is located on my XAMPP ), kindly take note that I'm using Android Studio Emulator.

我的代码大纲是创建“Registrar”对象,将其转换为JSON对象,并将该JSON对象转换为字符串,然后通过httpclient将该字符串作为帖子发送到PHP页面(位于我的XAMPP上) ),请注意我正在使用Android Studio Emulator。

My problem:

我的问题:

I don't know if the JSON file is received by the PHP server or not. Here is my code:

我不知道PHP服务器是否收到了JSON文件。这是我的代码:

Submit function:

提交功能:

public void goSubmit(View view) throws IOException {

    EditText nameEdit = (EditText) findViewById(R.id.nameEdit);
    EditText idEdit = (EditText) findViewById(R.id.idEdit);
    String name = nameEdit.getText().toString();
    String ID = idEdit.getText().toString();

    //Creating Student (Registrar) Object
    Student registrar = new Student();
    registrar.setMajor(majorEdit);
    registrar.setName(name);
    registrar.setId(ID);

    //Creating JSON String


    String registrarJSON = null;

    try {
    registrarJSON = ObjInJSON(registrar);
        Toast.makeText(this,  registrarJSON, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    //Posting JSON String on Remote PHP

    String PHPresponse = sendToRegistrationPHP(registrarJSON);
    Toast.makeText(this, PHPresponse, Toast.LENGTH_LONG).show();
    //Receive PIN from PHP as JSON String


    //Parsing JSON string to integer (pin)


    //Set PIN in registrar.getpin()


    //Passing the object to setPassword Activity condition registrar.pin =! null


}

Student class:

学生班:

 public class Student {

     String Id = "NULL" ;
     String Major = "NULL";
     String Name = "NULL";
     String Password = "NULL";
     String Pin = "NULL";


    public String getPin() {
        return Pin;
    }

    public void setPin(String pin) {
        Pin = pin;
    }

    public String getPassword() {
        return Password;
    }

    public void setPassword(String password) {
        Password = password;
    }

    public String getId() {
        return Id;
    }

    public String setId(String id) {
        Id = id;
        return id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getMajor() {
        return Major;
    }

    public void setMajor(String major) {
        Major = major;
    }



    }

Creating JSON object in string format:

以字符串格式创建JSON对象:

    protected String ObjInJSON(Student studentC) throws JSONException, UnsupportedEncodingException {
    String ID = studentC.getId();
    String Pin = studentC.getPin();
    String Major = studentC.getMajor();
    String Password = studentC.getPassword();
    String Name = studentC.getName();


    JSONObject json_obj = new JSONObject();

    json_obj.put("id", ID);
    json_obj.put("password", Password);
    json_obj.put("pin", Pin);
    json_obj.put("major", Major);
    json_obj.put("name", Name);

    return json_obj.toString();
}

Sending to PHP server:

发送到PHP服务器:

   public static String sendToRegistrationPHP(String jarr) throws IOException {
    StringBuffer response = null;
    try {

        String myurl = "10.0.2.2:8070/StudentaccistancePHP/MySqlTEST.php";
        URL url = new URL(myurl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        OutputStream out = new BufferedOutputStream(conn.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.write(jarr);
        writer.close();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println("Response in universal: " + response.toString());
    } catch (Exception exception) {
        System.out.println("Exception: " + exception);
    }

    if (response != null) {
        return response.toString();
    }
    else return "Not WORKING  !";
}

PHP server:

PHP服务器:

<?php


$json = file_get_contents('php://input');                           

$data = json_decode($json, true);
$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name']; 


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentassictance";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

$sql = "INSERT INTO students (id, major, name, password, pin)
VALUES ('$ID', '$major', '$name', '$password', '$pin')";

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




 ?>

However, nothing is inserted to the database.

但是,没有任何内容插入数据库。

1 个解决方案

#1


1  

First, you need to check what arrives as JSON into PHP side. You can

首先,您需要检查作为JSON到达PHP端的内容。您可以

var_dump($json,$data);

after json_encode() call and watch it to be a valid JSON. You can validate it here

在json_encode()调用之后,将其视为有效的JSON。你可以在这里验证它

Second, show you SHOW CREATE TABLE students

其次,向您展示SHOW CREATE TABLE学生

And third, rewrite everything to PDO as it supports named parameters and it would be theoretically easier for you to migrate to another DB engine later if needed. So it would be something like:

第三,将所有内容重写为PDO,因为它支持命名参数,如果需要,您在理论上更容易迁移到另一个数据库引擎。所以它会是这样的:

<?php


define('DSN','mysql:dbname=test;host=localhost');
define('DB_USERNAME','testuser');
define('DB_PASSWORD','testpassword');

$connect = new PDO(DSN, DB_USERNAME, DB_PASSWORD);

$json = file_get_contents('php://input');
/*$json = '{
    "id": "111",
    "password": "sfsdfsdf",
    "major": "Math",
    "name": "Test User"
}';*/

$data = json_decode($json, true);

$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name']; 

$sql = "INSERT INTO `students`(`id`,`major`, `name`, `password`, `pin`) VALUES(:id, :major, :name, :password, :pin)";   

$result = $connect->prepare($sql);

//bind parameter(s) to variable(s)
$result->bindParam( ':id', $ID, PDO::PARAM_INT );
$result->bindParam( ':major', $major, PDO::PARAM_STR );
$result->bindParam( ':name', $name, PDO::PARAM_STR );
$result->bindParam( ':password', $password, PDO::PARAM_STR );
$result->bindParam( ':pin', $pin, PDO::PARAM_STR );

$status = $result->execute();

if ($status)
{
    echo "New record created successfully <br>";

} else
{
    echo "Error: <br>" . 
    var_dump($connect->errorInfo(),$status);
}

$connect = null;

#1


1  

First, you need to check what arrives as JSON into PHP side. You can

首先,您需要检查作为JSON到达PHP端的内容。您可以

var_dump($json,$data);

after json_encode() call and watch it to be a valid JSON. You can validate it here

在json_encode()调用之后,将其视为有效的JSON。你可以在这里验证它

Second, show you SHOW CREATE TABLE students

其次,向您展示SHOW CREATE TABLE学生

And third, rewrite everything to PDO as it supports named parameters and it would be theoretically easier for you to migrate to another DB engine later if needed. So it would be something like:

第三,将所有内容重写为PDO,因为它支持命名参数,如果需要,您在理论上更容易迁移到另一个数据库引擎。所以它会是这样的:

<?php


define('DSN','mysql:dbname=test;host=localhost');
define('DB_USERNAME','testuser');
define('DB_PASSWORD','testpassword');

$connect = new PDO(DSN, DB_USERNAME, DB_PASSWORD);

$json = file_get_contents('php://input');
/*$json = '{
    "id": "111",
    "password": "sfsdfsdf",
    "major": "Math",
    "name": "Test User"
}';*/

$data = json_decode($json, true);

$ID = $data['id'];
$password = $data['password'];
$pin = "323232";
$major = $data['major'];
$name = $data['name']; 

$sql = "INSERT INTO `students`(`id`,`major`, `name`, `password`, `pin`) VALUES(:id, :major, :name, :password, :pin)";   

$result = $connect->prepare($sql);

//bind parameter(s) to variable(s)
$result->bindParam( ':id', $ID, PDO::PARAM_INT );
$result->bindParam( ':major', $major, PDO::PARAM_STR );
$result->bindParam( ':name', $name, PDO::PARAM_STR );
$result->bindParam( ':password', $password, PDO::PARAM_STR );
$result->bindParam( ':pin', $pin, PDO::PARAM_STR );

$status = $result->execute();

if ($status)
{
    echo "New record created successfully <br>";

} else
{
    echo "Error: <br>" . 
    var_dump($connect->errorInfo(),$status);
}

$connect = null;