Data in the database is not fetched from MySQL in PHP code

In my project, I was trying to enable each user to edit his profile but I'm getting stuck when I request the user data with a filter. When I pass the user id via the url, it returns {"success":0,"message":"No product found"} when in reality there is already a user with the same user id.
error.pnghere is the code for ProfileActivity
public class ProfileActivity extends Activity {
 
    EditText txtFname;
    EditText txtLname;
    EditText txtSsn;
    EditText txtEmail;
    EditText txtStreet;
    EditText txtCity;
    EditText txtState;
    EditText txtCountry;
    EditText txtZipcode;
    EditText txtTelephone;
    EditText txtCreatedAt;
    Button btnUpdate;
     
    String useremail;
    String uid;
 
    // Progress Dialog
    private ProgressDialog pDialog;
 
    // JSON parser class
    JSONParser jsonParser = new JSONParser();
 
    
    // url to update profile
    private static final String url_update_product = "http://10.0.0.8/android_login_api/update_profile.php";
 
 // single product url
    private static final String url_user_detials = "http://10.0.0.8/android_login_api/get_user_details.php";
 

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_USER = "user";
    private static final String TAG_UID = "uid";
   
    private static final String TAG_FNAME = "fname";
    private static final String TAG_LNAME = "lname";
    private static final String TAG_SSN = "ssn";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_STREET = "street";
    private static final String TAG_CITY = "city";
    private static final String TAG_STATE = "state";
    private static final String TAG_COUNTRY = "country";
    private static final String TAG_ZIPCODE = "zipcode";
    private static final String TAG_TELEPHONE= "telephone";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        if (android.os.Build.VERSION.SDK_INT > 9)
        {
       StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        }
 
        // save button
        btnUpdate = (Button) findViewById(R.id.btnUpdateProfile);
         
 
        // getting product details from intent
        Intent i = getIntent();
 
        // getting product id (pid) from intent
        uid = i.getStringExtra(TAG_UID);
        //useremail= i.getStringExtra(TAG_USEREMAIL);
 
        // Getting complete product details in background thread
        new GetProductDetails().execute();
 
        // save button click event
        btnUpdate.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                // starting background task to update product
                new SaveProductDetails().execute();
            }
        });
 
        
    }
 
    /**
     * Background Async Task to Get complete product details
     * */
    class GetProductDetails extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ProfileActivity.this);
            pDialog.setMessage("Loading user details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... params) {
 
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("uid", uid));
                        //params.add(new BasicNameValuePair("useremail", useremail));
                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                url_user_detials, "GET", params);
 
                        // check your log for json response
                        Log.d("Single User Details", json.toString());
 
                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json
                                    .getJSONArray(TAG_USER); // JSON Array
 
                            // get first product object from JSON Array
                            JSONObject user = productObj.getJSONObject(0);
 
                            // product with this pid found
                            // Edit Text
                            txtFname = (EditText) findViewById(R.id.inputFname);
                            txtLname = (EditText) findViewById(R.id.inputLname);
                            txtSsn = (EditText) findViewById(R.id.inputSsn);
                            txtEmail = (EditText) findViewById(R.id.inputEmail);
                            txtStreet = (EditText) findViewById(R.id.inputStreet);
                            txtCity = (EditText) findViewById(R.id.inputCity);
                            txtState = (EditText) findViewById(R.id.inputState);
                            txtCountry = (EditText) findViewById(R.id.inputCountry);
                            txtZipcode = (EditText) findViewById(R.id.inputZipcode);
                            txtTelephone = (EditText) findViewById(R.id.inputTelephone);
 
                            // display product data in EditText
                            txtFname.setText(user.getString(TAG_FNAME));
                            txtLname.setText(user.getString(TAG_LNAME));
                            txtSsn.setText(user.getString(TAG_SSN));
                            txtEmail.setText(user.getString(TAG_EMAIL));
                            if (json.isNull(TAG_STREET)){
                            	json.optString(TAG_STREET, "");
                            	 txtStreet.setText(user.getString(TAG_STREET));}
                            else
                            	txtStreet.setText(user.getString(TAG_STREET));

                            if (json.isNull(TAG_CITY)){
                            	json.optString(TAG_CITY, "");
                                txtCity.setText(user.getString(TAG_CITY));}
                            else
                            txtCity.setText(user.getString(TAG_CITY));
                            
                            if (json.isNull(TAG_STATE)){
                            	json.optString(TAG_STATE, "");
                            	 txtState.setText(user.getString(TAG_STATE));}
                            else
                            txtState.setText(user.getString(TAG_STATE));
                            
                            if (json.isNull(TAG_COUNTRY)){
                            	json.optString(TAG_COUNTRY, "");
                            	 txtCountry.setText(user.getString(TAG_COUNTRY));}
                            else
                            	
                            txtCountry.setText(user.getString(TAG_COUNTRY));
                            
                            if (json.isNull(TAG_ZIPCODE)){
                            	json.optString(TAG_ZIPCODE, "");
                            	 txtZipcode.setText(user.getString(TAG_ZIPCODE));}
                            else
                            txtZipcode.setText(user.getString(TAG_ZIPCODE));
                            
                            if (json.isNull(TAG_TELEPHONE)){
                            	json.optString(TAG_TELEPHONE, "");
                            	 txtTelephone.setText(user.getString(TAG_TELEPHONE));}
                            else 
                            txtTelephone.setText(user.getString(TAG_TELEPHONE));
                            
 
                        }else{
                            // product with pid not found
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }
 
    /**
     * Background Async Task to  Save product Details
     * */
    class SaveProductDetails extends AsyncTask<String, String, String> {
 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ProfileActivity.this);
            pDialog.setMessage("Saving Profile ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
 
        /**
         * Saving product
         * */
        protected String doInBackground(String... args) {
 
            // getting updated data from EditTexts
            String fname = txtFname.getText().toString();
            String lname = txtLname.getText().toString();
            String ssn = txtSsn.getText().toString();
            String email = txtEmail.getText().toString();
            String street = txtStreet.getText().toString();
            String city = txtCity.getText().toString();
            String state = txtState.getText().toString();
            String country = txtCountry.getText().toString();
            String zipcode = txtZipcode.getText().toString();
            String telephone = txtTelephone.getText().toString();
           
 
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_UID, uid));
            params.add(new BasicNameValuePair(TAG_FNAME, fname));
            params.add(new BasicNameValuePair(TAG_LNAME, lname));
            params.add(new BasicNameValuePair(TAG_SSN, ssn));
            params.add(new BasicNameValuePair(TAG_EMAIL, email));
            params.add(new BasicNameValuePair(TAG_STREET, street));
            params.add(new BasicNameValuePair(TAG_CITY, city));
            params.add(new BasicNameValuePair(TAG_STATE, state));
            params.add(new BasicNameValuePair(TAG_COUNTRY, country));
            params.add(new BasicNameValuePair(TAG_ZIPCODE, zipcode));
            params.add(new BasicNameValuePair(TAG_TELEPHONE, telephone));
 
            // sending modified data through http request
            // Notice that update product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                    "POST", params);
 
            // check json success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
 
                if (success == 1) {
                    // successfully updated
                    Intent i = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, i);
                    finish();
                } else {
                    // failed to update product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product uupdated
            pDialog.dismiss();
        }
    }
 
    
}

Open in new window

 

and this is the get_user_details.php

<?php
 
/*
 * Following code will get single product details
 * A product is identified by product id (pid)
 */
 
// array for JSON response

error_reporting(E_ALL ^ E_DEPRECATED);


$response = array();
 
// include db connect class
require_once 'include/DB_Connect.php';
 
// connecting to db
$db = new DB_CONNECT();
 
// check for post data
if (isset($_GET["uid"]) ) {
    $uid = $_GET['uid'];

     
    // get a product from products table
    $result = mysql_query("SELECT * FROM users WHERE uid= $uid");
    // $uiduser =$result["uid"];
   //$result2 = mysql_query("SELECT * FROM patients WHERE PatientID=  $uiduser");
 
    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {
 
            $row = mysql_fetch_array($result);  
            //$result2 = mysql_fetch_array($result2);  
 
    // JSON Node names

 
            $user = array();
            $user["uid"] = $row["uid"];
            $user["fname"] = $row["fname"];
            $user["lname"] = $row["lname"];
            $user["ssn"] = $row["SSN"];
            $user["email"] = $row["email"];
           // $user["street"] = $result2["StreetName"];
 	   // $user["city"] = $result2["City"];
 	   // $user["state"] = $result2["State"];
           // $user["country"] = $result2["Country"];
           // $user["zipcode"] = $result2["ZipCode"];
           // $user["telephone"] = $result2["TelephoneNumber"];
            $user["updated_at"] = $row["updated_at"];
            // success
            $response["success"] = 1;
 
            // user node
            $response["user"] = array();
 
            array_push($response["user"], $user);
 
            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No product found";
 
            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No product found";
 
        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}
?>

Open in new window


Any help would be appreciated.
error.png
Fatima113Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mark BullockQA Engineer IIICommented:
I would troubleshoot as follows:
1. hard code the user id in your SELECT statement. If that works, try #2
2. add a check for uid empty.  If it's not empty, try #3
3. print the value so you can see what value you have for uid

In future, you can use XDebug to help with debugging.
0
Fatima113Author Commented:
Thank you for your reply. It appears that the uid is actually empty and I think there is something wrong with ProfileActivity when passing the taq_uid but I could not figure it out.
0
Fatima113Author Commented:
oh sorry, when I print the value it gives 18 so, I think there is no problem with the ProfileActivity and the problem is with the query.
error3.png
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

Mark BullockQA Engineer IIICommented:
You're getting the uid value from the Intent.
I found a suggestion that getIntent changes if you go to another activity.
I noticed you have multiple calls to getIntent.
Could that be the problem?
0
Fatima113Author Commented:
I think there is no problem with the activity because when I was trying to pass an existing userid via the url, I get the same problem. See the attached error3 picture from the previous comment.
0
Mark BullockQA Engineer IIICommented:
Sorry. Could the substitution be inserting the quotes in addition to the number?
I am assuming the uid in your database is a number.
0
Fatima113Author Commented:
Yes, the uid in my database is a number so, do you mean that I should remove the quotes from $_GET['uid']?
0
Mark BullockQA Engineer IIICommented:
Your query should look like:
SELECT * FROM users WHERE uid= 18

Open in new window

and not
SELECT * FROM users WHERE uid= "18"

Open in new window

0
Fatima113Author Commented:
I think there is no problem with uid being a string because I print the value and it was a number. See attached picture.
error4.png
0
Mark BullockQA Engineer IIICommented:
Can you put the uid value in the query string and print out the query string?
0
Fatima113Author Commented:
I am not sure how I can print out the query because I tried echo $result; and echo mysql_query("SELECT * FROM users WHERE uid= 18"); but no result.
0
Mark BullockQA Engineer IIICommented:
Try putting the string in a variable and printing the variable, like:
$myquery = "SELECT * FROM users WHERE uid= $uid";
echo $myquery
0
Fatima113Author Commented:
Yes, I already tried it but I think that the query result is empty.
0
Fatima113Author Commented:
here is the screenshot from my database and as you can see there is already a user with uid=18.
db.png
0
Marco GasiFreelancerCommented:
I would try this:

$result = mysql_query("SELECT * FROM users WHERE uid='$uid'");

Open in new window

0
Chris StanyonWebDevCommented:
A few points of interest here:

On line 31, you don't check if it's not empty - you check if it's not false:

if ($result) {
   //valid query
} else {
   //invalid query
}

You should not be using the mySQL extension - it's deprecated and scheduled for removal - switch to mySQLi or PDO.

Double check your DB_Connect.php to make sure your not connecting to a different database - i.e. a test or development DB - I've seen it happen all too often.

Start adding in var_dumps - it'll help you visualize exactly what going on.

Change the error messages on lines 67 & 75 - it'll help you identify exactly which of the 2 if statements are returning false.

Be explicit when selecting your columns, rather than using the *

Here's a quick update - should at least allow you to see what's going on a little clearer:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// include db connect class
require_once 'include/DB_Connect.php';
$db = new DB_CONNECT();

$response = array();

// check for post data
if (isset($_GET['uid'])) {
    $uid = $_GET['uid'];

	$sqlStr = sprintf("SELECT uid, fname, lname, SSN, email, updated_at FROM users WHERE uid = %d", $uid);
    var_dump($sqlStr);
	
	$result = mysql_query($sqlStr);

    if ($result) {
        if (mysql_num_rows($result) > 0) {
            $row = mysql_fetch_array($result);  
            $response["success"] = 1;
            $response["user"] = $row;
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No product found";
        }
    } else {
        // problem running the query
        $response["success"] = 0;
        $response["message"] = "Query Failed";
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
}

echo json_encode($response);

Open in new window

0
Fatima113Author Commented:
Hi Chris, I had tried your code ant it gives {"success":0,"message":"Query Failed"}.See attached picture.
error5.png
0
Chris StanyonWebDevCommented:
I absolutely expected that and it reinforces what I said in my earlier post - you really, really should upgrade your code. If you continue using your current code, then it will stop working completely - sooner rather than later. When your hosting company upgrades PHP (and they will), the mysql extension will move from deprecated to obsolete.

As a very temporary tweak, add back in the DEPRECATED exception to error_reporting on line 2 of my code:

error_reporting(E_ALL ^ E_DEPRECATED);

Open in new window


This is not a solution, but it will allow you to test your code further.

Give me a minute, and I'll post a PDO version of your code
0
Chris StanyonWebDevCommented:
Hey Fatima,

Have a look through this code - it's an update that uses the PDO extension. It'll probably introduce a few new concepts if you've only used the mysql extension before, but hopefully it'll make sense. Obviously update the DB connection string to your own settings:

<?php
// Turn on error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
	// Connect to the database
	$dbh = new PDO('mysql:host=localhost;dbname=yourDB', 'username', 'password');
	$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
	$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
	die($e->getMessage());
}

$response = array();

if (isset($_GET['uid'])) {
	try {
		// Prepare the query
		$stmt = $dbh->prepare('SELECT uid, fname, lname, SSN, email, updated_at FROM users WHERE uid = :uid');

		// Execute the query
		$stmt->execute( array(':uid' => $_GET['uid']));
		
		// Fetch the user
		$user = $stmt->fetch();
		
		if ($user) {
			// We have a user
			$response["success"] = 1;
			$response["user"] = $user;
		} else {
			// We don't have a user
			$response["success"] = 0;
			$response["message"] = "No user found";
		}
		
	} catch (PDOException $e) {
		// There was a problem running the query
		$response["success"] = 0;
		$response["message"] = $e->getMessage();
	}
	
} else {
	// A required field is missing
	$response["success"] = 0;
	$response["message"] = "Required field(s) is missing";
}

echo json_encode($response);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Fatima113Author Commented:
Thank you very much Chris. It is  working now and I will try to change all my php files into PDO version. Again thank you and I will accept your solution.
success.png
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.