我在php上的代码:
<?php
$username ='root';
$password ='abc';
$hostname ='localhost';
$database ='test_xmpp';
$localhost = mysql_connect($hostname,$username,$password) or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database,$localhost);
$groupmates = array();
$abc=mysql_query('SELECT count(1) FROM groupchat');
$groupcount= mysql_result($abc,0);
$groupcount = $groupcount + 1;
echo $groupcount;
$admin = $_POST["admin"];
$groupname = $_POST["groupname"];
$groupmates = $_POST["groupmates"];
$sql="INSERT INTO groupchat (idgroupchat,groupname) VALUES ('$groupcount','$groupname')";
mysql_query($sql);
$b = '2';
$a = $groupmates[0];
$sql1="INSERT INTO groupuser (idgroup, username, admin) VALUES ('$groupcount','$a','$b')";
mysql_query($sql1);
?>
我在android上的代码:
public static class TestAsyncTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... urls) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("admin", admin));
nameValuePairs.add(new BasicNameValuePair("groupname", groupname));
for (int i=0;i<8;i++)
{
nameValuePairs.add(new BasicNameValuePair("groupmates",groupmates[i]));
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.102/webservice/issertgroup.php");
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
问题:$groupmates[0]
为空。我如何才能从Android传递数组?
我无法使用这种方法。请帮我解决这个问题。我在Google中搜索了很多参考文献,但仍然无法解决我的问题。
方法1
将参数作为来自android / java的数组元素传递,如下所示。
for (int i=0;i<8;i++)
{
nameValuePairs.add(new BasicNameValuePair("groupmates["+i+"]",groupmates[i]));
}
它只会在POST中传递一个数组,因此在PHP中,您可以按以下方式获取它:
<?php
$groupmates=$_POST['groupmates'];
// echo $groupmates[0];
// echo $groupmates[1]; <--process your elements as normal array.
?>
方法2:
您应该使用数组的json编码字符串。(我不是一个Android专家,所以不能提供将数组转换为json的代码段,但它很容易完成,您可能应该知道。)
nameValuePairs.add(new BasicNameValuePair("groupmates",jsonGroupmates));
并在php中使用以下代码:
$groupmates=json_decode($_POST['groupmates']);
那应该工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句