php - 将数据发送到 JSON 以实现数据库连接

标签 php android mysql database json

我有以下代码,它使用 Web 服务和 JSON 从数据库中选择数据。

MainActivity.java:

public class MainActivity extends Activity {
    RetrievingDataFromDatabase retrievingTask;
    TextView resultView;
    String s;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //StrictMode.enableDefaults();
        retrievingTask = new RetrievingDataFromDatabase();
        retrievingTask.execute((Void) null);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public void getData(){
        resultView = (TextView) findViewById(R.id.textView1);
        String result = "";
        InputStream isr = null;
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://PHP FILE LINK");
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();
        }
        catch(Exception e){
            Log.e("log_tag","Error in http connection"+e.toString());
            resultView.setText("Couldnt connect to database");
        }
        //converting to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null){
                sb.append(line + "\n");
            }
            isr.close();
            result = sb.toString();
        }
        catch(Exception e){
            Log.e("log_tag", "Error converting result"+ e.toString());
        }

        //parse data
        try{
            s = "";
            JSONArray jArray = new JSONArray(result);
            for(int i = 0;i<jArray.length();i++){
                JSONObject json = jArray.getJSONObject(i);
                s = s + json.getString("StdId").toString();
            }
            //resultView.setText(s);
        }
        catch(Exception e){
            Log.e("Log_tage", "Error Parsing Data"+e.toString());
        }
    }

    class RetrievingDataFromDatabase extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            getData();
            return null;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            resultView.setText(s);
        }
    }
}

JSONParser.java:

    public class JSONParser {
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";

        public JSONParser() {

        }

        public JSONObject getJSONFromUrl(String url) {

            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();           

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            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();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            // return JSON String
            return jObj;

        }

}

PHP 文件:

<?php

$con = mysql_connect("***","***","***");

if (!$con)
    {
    die('Could not Connect:' . mysql_error());
    }

mysql_select_db("database_name",$con);

$result = mysql_query("SELECT STID FROM database_name");

while($row = mysql_fetch_assoc($result))
    {
       $output[]=$row;
    }

print(json_encode($output));

mysql_close($con);

?>

这部分代码从数据库检索数据,我需要帮助来反转该过程(将数据发送到 PHP 文件并根据该值选择数据。例如:

1- 从 Android 应用程序接收到 php 文件的数据 2- 从 PHP 文件中的数据库行中选择将类似于:

"select * from DB_name WHERE ".$valueFromAndroidApp

3-从数据库检索数据到 PHP 文件,然后 PHP 将结果发送到 Android 应用程序。

抱歉,解释很长,但我需要帮助。

最佳答案

我会给你一个示例代码,用于从android标记当前位置并将详细信息发送到服务器php文件并在php中创建一个新记录..这里我已经给出了php文件..我假设你知道如何从 android 解析 json。如果没有的话我也给你..

// check for required fields
 if (isset($_POST['location']) && isset($_POST['email']) && isset($_POST['lat']) && isset($_POST['longitude'])) {

    $location = $_POST['location'];
    $email = $_POST['email'];
    $lat = $_POST['lat'];
    $longitude = $_POST['longitude'];

    require_once 'config.php';
    // connecting to mysql
    $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    // selecting database
    mysql_select_db(DB_DATABASE);

   // mysql inserting a new row
   $result = mysql_query("INSERT INTO marked_locations(location, email,lat,longitude) VALUES('$location', '$email', '$lat','$longitude')");
   .....
   ..

位置、电子邮件、纬度、经度值来自 Android 的 json

关于php - 将数据发送到 JSON 以实现数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20048129/

相关文章:

mysql - 具有多个值的 SQL Where 子句

php - 身份不明的 PHP 和 PDO 执行时间较长

php - 数据不断变化时 "Recently Online"列表的排序策略(PHP)

php - mySQL另一种组合查询

未找到用于 native 代码编译的 Android bitmap.h

c# - 禁用 Android 双击 Xamarin Forms 标签

php - 使用 PDO 转换我的开发后,代码无法正常工作

php - 从 while 循环中获取计数器的更简单方法?

php - 将索引转换为指定字符串的更简洁方法?

java - 在textView中一一显示ArrayList中的值