【问题标题】:Dynamically change mysql query in php with java (android)使用java(android)动态更改php中的mysql查询
【发布时间】:2012-07-12 18:17:38
【问题描述】:

我正在为我的 java/android 应用程序使用 MySQL 数据库和 php。 我对php没有任何经验。

这是我的 php 文件 (getAllDataFromSomeTable.php)

<?php
mysql_connect("someHosturl","someUsername","somePassword");
mysql_select_db("databasename");

$q=mysql_query("SELECT * FROM sometable");
while($e=mysql_fetch_assoc($q))
    $output[]= $e;

print(json_encode($output));

mysql_close();
?>

我在 Java 中使用 HttpPosts 和类似的东西。 这样我就可以从'sometable'中获取所有数据

但如果我想使用不同的查询,例如“从用户名 = 'thisuser' 的某个表中选择前 1 个”。我怎样才能在java中动态改变它? 我的 php 文件应该如何看,java 中的代码应该如何看? 这是我现在的代码:

String result = "";
    List<? extends NameValuePair> licenses = (List<? extends NameValuePair>) new ArrayList<DriversLicense>();
    InputStream is = null;
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://some-url.com/getAllDataFromSomeTable.php");
        httpPost.setEntity(new UrlEncodedFormEntity(licenses));
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e){
        Log.d("httpclient tag", e.getMessage());
    }

    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();
        Log.d("result is", result);
    }catch(Exception e){
         Log.d("log-tag", "Error converting result "+e.toString());
    }

    try{
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                Log.d("from jsonObject", "id= " + json_data.getInt("Id") + ", number = "
                        +json_data.getString("Number"));
        }
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }

【问题讨论】:

    标签: java php android mysql dynamic


    【解决方案1】:

    您为什么不尝试在请求中添加参数?

    例如:

    http://some-url.com/getAllDataFromSomeTable.php?table=difftable&whereField.1=username&whereValue.1=xyz&whereField.2=surname&whereValue.2=Smith

    这样,您需要解析这些参数并根据传递的数据构建查询。 我认为上述请求会进行此查询:

    select * from difftable where username = 'xyz' and surname ='Smith'
    

    另一方面,这就是网络服务的用途,所以如果可能的话,我会考虑类似的事情。

    【讨论】:

    • 谢谢,我会试试看,它可能会这样工作,但就像我说的,我没有 web 服务或 php 的经验:p tnx 快速响应。但是我应该如何在 php 文件中编写查询?我可以在里面放一些像“$query”这样的东西,而不是在 java “someurl.com/getda...table.php?query=" + queryString ;
    • 是的,这是可能的。然后在 php 中,您可以使用以下命令获取 url 的查询参数: $_GET['query']跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2021-08-05
    • 2021-11-01
    • 1970-01-01
    • 2013-03-25
    • 2017-01-22
    相关资源
    最近更新 更多