1

我正在尝试将多个 (1-50) 条目从 Android 应用程序插入到外部 Mysql 数据库。我完美地得到了一个 PHP 脚本来处理单个 INSERT 查询。但是到目前为止,我未能使这项工作适用于整个条目,这很可能是由于我对 PHP 的了解有限。

安卓代码:

List<NameValuePair> upload_array = new ArrayList<NameValuePair>();
upload_array.add(new BasicNameValuePair("mFirstname[0]", "FirstName 1"));
upload_array.add(new BasicNameValuePair("mFirstname[1]", "FirstName 2"));
upload_array.add(new BasicNameValuePair("mLastname[0]", "LastName 1"));
upload_array.add(new BasicNameValuePair("mLastname[1]", "LastName 2"));
upload_array.add(new BasicNameValuePair("mNickname[0]", "NickName 1"));
upload_array.add(new BasicNameValuePair("mNickname[1]", "NickName 2"));

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://url/script.php");
HttpResponse response = null;
try {
    httppost.setEntity(new UrlEncodedFormEntity(upload_array));
    response = httpclient.execute(httppost);
} catch (Exception e) {
    e.printStackTrace();
}

在 PHP 中:

<?php

$connect = mysqli_connect("***","***","***", "***");

if(mysqli_connect_errno($connect))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
    echo "success";
}

$query = mysqli_prepare("INSERT INTO `namelist` (`firstname`,`lastname`,`nickname`)
    VALUES(?,?,?)");

$mFirstname = $_POST['mFirstname'];
$mLastname = $_POST['mLastname'];
$mNickname = $_POST['mNickname'];

foreach($mFirstname as $key as $key => $value) {
    $query->bind_param('sss',$value["mFirstname"],$value["mLastname"],$value["mNickname"];
    $query->execute();
}

mysqli_close($connect);
?>

代码的 Android 部分是否已经发生错误,或者这个 PHP 脚本只是没有读取我正确发送的数据?任何见解都将非常受欢迎。

4

1 回答 1

1

好的,我使用 JSON 数组完成了这项工作。如果有人使用它,它是这样的:

Android,创建 JSON 字符串:

//Create JSON string start
String json_string ="{\"upload_fishes\":[";

//Repeat and loop this until all objects are added (and add try+catch)
JSONObject obj_new = new JSONObject();
obj_new.put("fish_id", your_looped_string_1[i]);
obj_new.put("fish_lat", your_looped_string_2[i]);
obj_new.put("fish_lon", your_looped_string_3[i]);
json_string = json_string + obj_new.toString() + ",";

//Close JSON string
json_string = json_string.substring(0, json_string.length()-1);
json_string += "]}";

Android 向 PHP 发送数据(添加 try+catch):

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

String url = "http://yourserver.com/script.php";

HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json_string.getBytes("UTF8")));
request.setHeader("json", json_string);
HttpResponse response = client.execute(request);

Log.d("FISHY", response.getStatusLine().toString());

PHP 脚本:

<?php

//CONNECT TO THE DATABASE
 $DB_HOST = 'yourhost.com';
 $DB_USER = 'user';
 $DB_PASS = 'password';
 $DB_NAME = "db_name";

 $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);

 if(mysqli_connect_errno())
{
//    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//    echo "Connected to MySQL";
}


   $postdata = file_get_contents("php://input"); 
   $data = json_decode($postdata, true);

   if (is_array($data['upload_fishes'])) {
      foreach ($data['upload_fishes'] as $record) {
        $fid = $record['fish_id'];
        $flat = $record['fish_lat'];
    $flon = $record['fish_lon'];

        mysqli_query($mysqli,"INSERT INTO `fishes`(`fish_type_id`, `fish_lat`, `fish_lon`) VALUES ($fid, $flat, $flon)");
      }
   }


mysqli_close($mysqli);
?>
于 2013-09-13T11:49:36.687 回答