I'm trying to upload data into my mysql database.
The code below doesn't throw any errors, but when I check the database, the data isn't there.
Can anyone see what I am doing wrong? It doesnt even seem to run the php.
I have a feeling it is a problem with the php code. It used to work with httppost, but recently, the data started to get mixed up, and it would hang. I saw that httppost is depreciated, so am trying to use HttpURLConnection instead.
Here is the java:
public void uploadmydata() throws Exception {
URL url = new URL("http://www.myurl.co.uk/test5.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("name", "Joe"));
params.add(new BasicNameValuePair("surname", "Bloggs"));
params.add(new BasicNameValuePair("country", "UK"));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
urlConnection.connect();
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
and here is my php:
session_start();
//CREATE CONNECTION
$con=mysql_connect("00.00.00.00","my_username","password") or die (mysql_error());
//CHECK CONNECTION
if (!$con) { die('Could not connect to MySQL: ' . mysql_error());
}
else
//echo 'connected!';
//SELECT SITE DATABASE
mysql_select_db("my_database", $con);
$name=$_POST['name'];
$surname=$_POST['surname'];
$country=$_POST['country'];
//sql query
mysql_query("insert into myTable (name, surname, country) values('{$name}','{$surname}','{$country}')");
mysql_close();