无法使用namevaluepair将字符串发送到php文件

时间:2016-02-08 07:30:51

标签: php android mysql

我正在尝试使用namevaluepair将字符串发送到php脚本。但我无法在另一边收到它。这是我的代码。

protected String doInBackground(String... args) {
  ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
  nameValuePairs.add(new BasicNameValuePair("Username",code ));
  Log.v("username", code);

  DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
  HttpPost httppost = new HttpPost("http://192.168.42.21:8080/sellapp/menuitem.php");

  // Depends on your web service
  httppost.setHeader("Content-type", "application/json");

  InputStream inputStream = null;
  String result = null;


  try {
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    inputStream = entity.getContent();
    // json is UTF-8 by default
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
      sb.append(line + "\n");
    }
    result = sb.toString();


  } catch (Exception e) {
    // Oops
  }
  finally {
    try{if(inputStream != null)inputStream.close();}catch(Exception squish {}
  }
  return result;
}

这里我想将字符串代码中的值传递给我的php脚本。我的PHP脚本是

$con = mysqli_connect(HOST,USER,PASS,DB);
$cst_id=$_REQUEST['Username'];
// $cst_id= 'cus02';
$sql = "
  select
  cust_code, segment_type, cust_name, cust_address, cust_payment_type, cust_credit_limit, cust_cr_balance
 from customer where cust_code='".$cst_id."'
";

$res = mysqli_query($con,$sql);

$result = array();
while($row = mysqli_fetch_array($res)){
  array_push(
    $result,
    [
      'cust_id'=>$row[0],
      'cust_seg'=>$row[1],
      'cust_name'=>$row[2],
      'cust_type'=>$row[3],
      'cust_ad'=>$row[4],
      'cust_cr'=>$row[5],
      'cust_bl'=>$row[6]
    ]
  );
}

echo json_encode(array("result"=>$result));

mysqli_close($con);

当我直接向php提供值时,它可以工作。但是通过名称/值对,它返回一个空数组作为结果。

请帮我解答。我尝试过与之相关的问题。但没效果。

1 个答案:

答案 0 :(得分:0)

<?php


    $con = mysqli_connect(HOST,USER,PASS,DB);

    $cst_id = $_POST['Username']; // --------- not $_REQUEST['Username'];

    // $cst_id= 'cus02';

    $sql = "select  cust_code,segment_type,cust_name,cust_address,cust_payment_type,cust_credit_limit,cust_cr_balance from customer where cust_code='".$cst_id."' ";

    $res = mysqli_query($con,$sql);


    $result = array();
    while($row = mysqli_fetch_array($res)){
        array_push($result,
            ['cust_id'=>$row[0],
            'cust_seg'=>$row[1],
            'cust_name'=>$row[2],
            'cust_type'=>$row[3],
            'cust_ad'=>$row[4],
            'cust_cr'=>$row[5],
            'cust_bl'=>$row[6]
            ]);
    }

    //echo json_encode(array("result"=>$result));
    echo json_encode($result); 

    mysqli_close($con);


?>
相关问题