gpt4 book ai didi

java - 使用 php 和 JSON 将 android 连接到 mySQL

转载 作者:行者123 更新时间:2023-11-30 23:01:10 24 4
gpt4 key购买 nike

我正在尝试创建一个通过 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 的形式出现。有人可以告诉我我做错了什么或给我提示以获得结果吗?提前致谢!

最佳答案

这是从 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
}

关于java - 使用 php 和 JSON 将 android 连接到 mySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23896723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com