通过Android插入数据库

时间:2015-05-08 13:30:28

标签: php android database basicnamevaluepair

我有以下问题:

我已经使用XAMPP建立了一个数据库,并且我已经编写了4个PHP脚本来插入并显示它的内容。到现在为止工作正常。数据库有两列body,并且都可以处理类型文本,并且可以在其中写入一些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);

&GT;

我可以在模拟器上运行应用程序,但没有任何反应,所以我的数据库中没有新的条目。有人可以向我解释一下,我是如何在PHP中做到这一点的?或者android代码中是否有错误?

rikojir

0 个答案:

没有答案