0

我有以下问题:

我已经使用 XAMPP 建立了一个数据库,并且我编写了 4 个 PHP 脚本来插入和显示它的内容。现在效果很好。该数据库有两列 body 和 address 都是 text 类型的,它可以在其中写入一些 sms 数据。

现在我想从我的 Android 应用程序插入。为了实现这一点,我在我的应用程序中编写了这几行代码:

        //the sms to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("body","testbody"));
        nameValuePairs.add(new BasicNameValuePair("address", "testaddress"));

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/sms/addsms.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

现在的问题是 - 如果上面的代码没有错误 - 我如何将这些 BasicNameValuePairs 传递给我的 PHP 变量?我的 PHP 脚本如下所示:

<?php

//This is my problem: How can I write the values from inside 
//my android application in to those variables here? :(

//Getting the JSON data sent by the android app
$json_body = $_REQUEST['body'];
//Converting it into a standard class object
$obj_body = json_decode($json_body, true);
//Getting the value associated to the 'body' property
$body = $obj_body->'body';

//Getting the JSON data sent by the android app
$json_address = $_REQUEST['address'];
//Converting it into a standard class object
$obj_address = json_decode($json_address, true);
//Getting the value associated to the 'body' property
$address = $obj_address->'address';


//Connecting to database
require_once('mysqli_connect.php');

//Defining the query for inserting
$query = "INSERT INTO sms (body, address) VALUES (?,?)";

//Preparing the statement to be executed
$stmt = mysqli_prepare($dbc, $query);

//Binding the parameters to the statement
mysqli_stmt_bind_param($stmt, "ss", $body, $address);

//Executing the statement
mysqli_stmt_execute($stmt);

?>

我可以在模拟器上运行该应用程序,但没有任何反应,因此我的数据库中没有新条目。有人可以向我解释一下,我如何在 PHP 中做到这一点?还是android代码有问题?

里克吉尔

4

0 回答 0