在Android上通过WAMP访问mySQL



我很难理解如何准确地配置WAMP远程(不是局域网)访问由Android应用程序到我用它创建的SQL数据库。我明白,我不应该从应用程序直接连接到数据库,而是使用PHP脚本查询数据库并返回结果。我不理解的是这一切是如何配合在一起的,我在哪里放PHP脚本,我如何访问它们,我如何允许并连接到web服务器从数据库中获取数据。

我已经跟随并搜索了很多教程,但他们似乎都只处理使用wamp在本地主机,我可以成功地访问本地数据,但我难住了如何设置所有这些,以便我可以从我的android设备上的任何互联网连接查询数据库。

任何关于如何实现这一点的建议将是非常感激的。

你必须上传你的php脚本到你的服务器:

示例:你的php在:myserver.com/myscript.php

在你的Android应用程序中,你张贴你的变量,你连接你的php脚本与HttpClient:

    URL_TO_YOUR_SCRIPT = "myserver.com/myscript.php";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("userId", userId));
    HttpClient httpclient = new DefaultHttpClient();
    // specify the URL you want to post to
    HttpPost httppost = new HttpPost(URL_TO_YOUR_SCRIPT);
    try {
        // create a list to store HTTP variables and their values
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        HttpResponse response = httpclient.execute(httppost);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
            HttpEntity getResponseEntity = response.getEntity();
            return getResponseEntity.getContent();
        } else {
            Log.e("ERROR", statusLine.getStatusCode() + "");
            HttpEntity getResponseEntity = response.getEntity();
            return getResponseEntity.getContent();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

在你的php中:

<?
    $userId=$_REQUEST['userId'];
    ....
   // in general you return a json string to get status and result
?>

最新更新