php - HTTPPOST Android to Server
Get the solution ↓↓↓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);
?>
Answer
Solution:
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 callmysql_real_escape_string
on your inputs to guard against SQL injection attacks.
Answer
Solution:
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...
Answer
Solution:
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"
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught error: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.