I can't connect to database in PHP. My Android code is:
private void connecttodb() {
String result = "";
InputStream isr = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", etusername.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password", etpassword.getText().toString().trim()));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://jcprivatesite.uboxi.com/teenpatti/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("mylog", "Error in http connection " + e.toString());
}
}
and my PHP code is:
http://jcprivatesite.uboxi.com/teenpatti/php1.txt:
<?php
error_reporting(0);
require_once('databaseClass.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query="INSERT INTO `u624768762_teenp`.`login` (`username`, `password`) VALUES ($username, $password);";
$result=$link1->query($query);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysqli_close($con);
?>
I really tried many codes but it is not helping. One strange thing about this is that Android is executing the link(url), but it is not posting. I mean when I replace code with:
http://jcprivatesite.uboxi.com/teenpatti/php2.txt:
<?php
error_reporting(0);
require_once('databaseClass.php');
$username = 'username';
$password = 'password';
$query="INSERT INTO `u624768762_teenp`.`login` (`username`, `password`) VALUES ($username, $password);";
$result=$link1->query($query);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysqli_close($con);
?>
my database is updating. But when I place post methods or calls($_POST['username']
) it is not updating. Please help guys. I would be greatful if you could include sample code.
Android is single thread application, whenever you perform network task like getting JSON from a url you need to do it through AsyncTask (most probably), it is created to do such tasks.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
call it like
new DownloadFilesTask().execute(url1, url2, url3);
For more information on AsyncTask, follow instructions here