I want to insert N number of rows in a mysql table called USERS. For inserting a single row I write this code (it works):
PHP side: insert_user.php
<?php
$mysqli = new mysqli('hostname', 'username','password', 'dbname');
if (mysqli_connect_errno()) {
printf("Can't connect Errorcode: %s\n", mysqli_connect_error());
exit;
}
if ($result = $mysqli->prepare("INSERT INTO `users` (`email`, `imei`) VALUES (?,?)")) {
$email = $_POST['email'];
$imei = $_POST['imei'];
$result->bind_param("ss", $email, $imei);
$result->execute();
$result->close();
printf("Insert OK");
} else {
printf("Insert KO. ERROR: %s",mysqli_error());
}
$mysqli->close();
?>
JAVA side
public void insertUser(String email
, String imei) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("imei", imei));
// send them on their way
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myserver.com/insert_user.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
} catch (e) {
e.printStackTrace();
}
}
THE QUESTION
I need a little complete example for “insert_multi_user.php” and the relative java method, to pass more rows (using an Array? a Collection? I don’t know…).
For instance, replacing this java lines:
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("imei", imei));
with arrays (?):
nameValuePairs.add(new BasicNameValuePair("email", email[]));
nameValuePairs.add(new BasicNameValuePair("imei", imei[]));
and, in php, replacing:
$email = $_POST['email'];
$imei = $_POST['imei'];
with:
$email[] = $_POST['email'];
$imei[] = $_POST['imei'];
(obviously the above code is only to give you the idea, it is not correct…)
I spent days with no luck 🙁
Thank you,
Geltry
Just wrap your code with for loop
If you have a record/array with users you can do something like
But to do that you have to change the way you submit your data, so don’t do it one by one rather submit a CSV file for example, parse it with
fgetcsvand run through each of the records.On the Java side you can also pass a POST array:
The other options is to send the data in JSON format to the PHP script and use
json_decode