【问题标题】:Connecting android to mySQL using php and JSON使用 php 和 JSON 将 android 连接到 mySQL
【发布时间】:2014-05-27 18:42:55
【问题描述】:

我正在尝试创建一个通过 php 和 JSON 连接到 mySQL 数据库的 android 应用程序。 这是我在服务器上的 php 文件:

<?php
$host="my_host";
$username="my_name";
$password="my_password";
$db_name="my_db_name";

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT    UserID, DisplayName
FROM      User
WHERE     (UserName LIKE '%it%') OR (DisplayName LIKE '%it%')"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['UserRes'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
?> 

这是我的 JSON java 类代码:

public class JSONClass extends AsyncTask<String,Void,String>{

public HashMap<String, String> tbl = new HashMap<String, String>();
private Context context;

public JSONClass(Context context) {
    this.context = context;
}

@Override
protected String doInBackground(String... arg0) {
    try{
        String link = "some url";
        URL url = new URL(link);
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(link));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line="";
        while ((line = in.readLine()) != null) {
            sb.append(line);
            break;
        }
        in.close();
        return sb.toString();
    }catch(Exception e){
        return new String("Exception: " + e.getMessage());
    }
}
}

我是新手,只想了解基础知识并从那里开始工作。 php 文件应该返回一行作为答案,但据我所知,该函数属于 try - catch 部分。我知道结果应该以 HashMap 的形式出现。有人可以告诉我我做错了什么或给我一个提示以获得结果吗?提前谢谢!

【问题讨论】:

  • 您是否希望通过运行 mysql 查询仅显示一行?
  • 是的,我是一行,用户 ID - int 和显示名称 - varchar(254)

标签: java php android mysql json


【解决方案1】:

这是您从url 获取数据的方式,其中url 是您的PHP 脚本的网址:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
JSONArray ja = new JSONArray(result);
for(int i = 0 ; i < ja.length() ; i++){
  String name = ja.getJSONObject(i).getString("name"); //write name of column
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-21
    • 2012-11-06
    • 1970-01-01
    • 2017-06-15
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多