Reputation: 3190
I'm working on a program that sends data to a server. The server is receiving my data, but only the last bit of it. Here's my Android code:
ArrayList<NameValuePair> j2 = new ArrayList<NameValuePair>();
j2.add("drink_name", "rootbeer")
j2.add("drink_name", "pepsi")
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("kubie.dyndns-home.com/R2Bar2/getingredients.php");
httppost.setEntity(new UrlEncodedFormEntity(j2));
HttpResponse response = httpclient.execute(httppost);
responseText = EntityUtils.toString(response.getEntity());
But it's only adding the last entry (pepsi) to the database. Here's my php:
<?php
$handle = mysql_connect('localhost','root','xxxx');
if($handle==false)
{
die('No database connection');
}
$result = mysql_query("TRUNCATE TABLE 'available_ingredients'");
$db=mysql_select_db('r2bar2');
$query='INSERT INTO available_ingredients (drink_name) VALUES ("'.$_POST["drink_name"].'")';
$result=mysql_query($query);
?>
Upvotes: 2
Views: 536
Reputation: 8951
try this
j2.add(new BasicNameValuePair("drink_name[]", "rootbeer"));
j2.add(new BasicNameValuePair("drink_name[]", "pepsi"));
what you're putting in your entity is a List of NameValuePair -- so each thing you add should be a NameValuePair, and the BasicNameValuePair is one of those
in the php
<?php
foreach ($_POST["drink_name"] as $drink_name) {
$query=...
$result=...
}
?>
but a note of caution -- make sure you call mysql_real_escape_string
on your inputs to guard against SQL injection attacks.
Upvotes: 3
Reputation: 20885
You set the same key twice, so when the server receive your request it sees only the last value for drink_name, which is "Pepsi" because it overwrites "rootbeer"
Upvotes: 0
Reputation: 236
Try to change the name of the parameters to below (from the Android code):
j2.add("drink_name[]", "rootbeer"); j2.add("drink_name[]", "pepsi");
And in your PHP:
$drink_names = array($_POST['drink_name']);
Hope this helps...
Upvotes: 1