Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

MASUKKAN beberapa entri dari Android -> PHP -> MYSQL

Oke, saya membuat ini berfungsi menggunakan JSON Array. Jika ada yang pernah menggunakannya, begini caranya:

Android, buat String 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 mengirim data ke PHP (tambahkan 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());

Skrip 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);
?>



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana cara memeriksa apakah INSERT berjalan dengan baik dalam fungsi tersimpan?

  2. FIND_IN_SET dengan dua string

  3. Mengapa saya mendapatkan pengecualian server MySQL telah hilang di Django?

  4. Bagaimana cara membuat koneksi database saya aman?

  5. Gabung dalam dengan 3 tabel di mysql