S
S
saliev932015-01-27 02:32:04
Java
saliev93, 2015-01-27 02:32:04

How to get data from database using json?

Here is a piece of code responsible for getting data for the selected id from the database

class GetProgramDetails extends AsyncTask<String, String, String> {
 
        /**
         * Перед началом показать в фоновом потоке прогресс диалог
         **/
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditProgramActivity.this);
            pDialog.setMessage("Loading program details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Получение детальной информации о продукте в фоновом режиме
         **/
        protected String doInBackground(String... params) {
 
            // обновляем UI форму
        	runOnUiThread(new Runnable() {
        		public void run(){
        	
                   // проверяем статус success тега
                    int success;
                    try {
                        // Список параметров
                        List<NameValuePair> assisstent = new ArrayList<NameValuePair>();
                        assisstent.add(new BasicNameValuePair("id_program", id_program));
 
                        // получаем продукт по HTTP запросу
                        JSONObject json = jsonParser.makeHttpRequest(url_program_details, "GET", assisstent);
 
                        Log.d("Single Program Details", json.toString());
 
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // Успешно получинна детальная информация о продукте
                            JSONArray programObj = json.getJSONArray(TAG_PROGRAM);
 
                            // получаем первый обьект с JSON Array
                            JSONObject program = programObj.getJSONObject(0);
 
                            // продукт с pid найден
                            // Edit Text
                            txtDay = (EditText) findViewById(R.id.inputDay);
                            txtType = (EditText) findViewById(R.id.inputType);
                            txtList = (EditText) findViewById(R.id.inputList);
 
                            // покаываем данные о продукте в EditText
                            txtDay.setText(program.getString(TAG_DAY_OF_WEEK));
                            txtType.setText(program.getString(TAG_TYPE));
                            txtList.setText(program.getString(TAG_LIST));
 
                        }else{
                            // продукт с pid не найден
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
        		}
        	});
        
            return null;
        }
 
        /**
         * После завершения фоновой задачи закрываем диалог прогресс
         **/
        protected void onPostExecute(String file_url) {
            // закрываем диалог прогресс
            pDialog.dismiss();
        }
    }

Here is the php that is responsible for this on the server:
<?php

$response = array();

$DB_USER = "xxx"; // db user
$DB_PASSWORD = "xxx"; // db password 
$DB_DATABASE = "xxx"; // database name
$DB_SERVER = "xxx"; // db server

$con = mysql_connect("$DB_SERVER", "$DB_USER", "$DB_PASSWORD") or die(mysql_error());

if (isset($_GET["id_program"])) {
    $id_program = $_GET['id_program'];
 
    $result = mysql_query("SELECT * FROM program WHERE id_program = $id_program");
 
    if (!empty($result)) {
        if (mysql_num_rows($result) > 0) {
            
            $result = mysql_fetch_array($result);
 
            $program = array();
           
            $program["id_program"] = $result["id_program"];
            $program["day_of_week"] = $result["day_of_week"];
            $program["type"] = $result["type"];
            $program["list"] = $result["list"];

            $response["success"] = 1;
 
            $response["program"] = array();
 
            array_push($response["program"], $program);
             
            echo json_encode($response);
        } else {
            $response["success"] = 0;
            $response["message"] = "No product found";
 
            echo json_encode($response);
        }
    } else {
        $response["success"] = 0;
        $response["message"] = "No product found";
 
        echo json_encode($response);
    }
} else {
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    echo json_encode($response);
}
?>

The server returns a response - No product found. success:0 what's the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Radar, 2015-01-27
@RadarWeb

And what is id_programm?
Maybe this is better:

$result = mysql_query("SELECT * FROM `program` WHERE `id_program` = '" . $id_program . "'");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question