无法从Android连接到PHP数据库

时间:2014-11-14 06:50:17

标签: php android mysql database

我无法用PHP连接到数据库。 我的Android代码是:

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());
    }
}

我的PHP代码是:

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);
?>

我真的尝试了很多代码,但它没有帮助。关于这个的一个奇怪的事情是Android正在执行链接(url),但它没有发布。我的意思是当我用以下代码替换代码时:

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);
?>

我的数据库正在更新。但是当我发布post方法或调用($_POST['username'])时,它不会更新。 请帮帮我们如果你能包含示例代码,我会很高兴。

1 个答案:

答案 0 :(得分:0)

Android是单线程应用程序,无论何时执行网络任务,例如从网址获取JSON,您需要通过AsyncTask(最有可能)执行此操作,就会创建它来执行此类任务。

 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");
     }
 }

称之为

new DownloadFilesTask().execute(url1, url2, url3);

有关AsyncTask的详细信息,请按照here

说明操作