1

EDIT: 20020-20020/practise.mysql_php_json I/System.out: org.json.JSONException: Value br of type java.lang.String cannot be converted to JSONObjectww is the message in the terminal I'm getting.

I am working to get a simple insert and retrieve application to work in android by following a tutorial on youtube. Should be fairly simple and I am able to post the user info to the online database, but when I go to retrieve it, nothing happens. Not getting any errors, just not getting any response in JSON.

I am just starting to work with JSON and php both, so I don't know if I'm just not getting something or missing something small.

Here is my connection.php which I know my credentials are correct because I can insert.

<?php

    define('hostname', '--------');
    define('user', '---------');
    define('password', '-------');
    define('database', '------------------');

    $connect = mysqli_connect(hostname, user, password, database);

?>

Here is my insertUser.php

<?php

if($_SERVER["REQUEST_METHOD"]=="POST") {
    require 'connection.php';
    createUser();
}

function createUser() {
    global $connect;

    $name = $_POST["name"];
    $email = $_POST["email"];
    $password = $_POST["password"];

    $query = " Insert into user_table(user_name, user_email, user_password) values ('$name','$email','$password');";

    mysqli_query($connect, $query) or die (mysqli_error($connect));
    mysqli_close($connect);
}

?>

Here is my showUsers.php

<?php

if($_SERVER["REQUEST_METHOD"]=="GET"){
    include 'connection.php';
    showStudent();
}
function showStudent()
{
    global $connect;

    $query = " Select * FROM users; ";

    $result = mysqli_query($connect, $query);
    $number_of_rows = mysqli_num_rows($result);

    $temp_array  = array();

    if($number_of_rows > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $temp_array[] = $row;
        }
    }

    header('Content-Type: application/json');
    echo json_encode(array("users"=>$temp_array));
    mysqli_close($connect);

}

?>

Now here's my Android application code in the Main Activity. This is supposed to just get the name, email, and password of the users in my database. I have another onclick method to insert the users.

showButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        JsonObjectRequest jsonObjectRequest; = new JsonObjectRequest(Request.Method.GET, showURL, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray users = response.getJSONArray("users");
                    for(int i=0; i<users.length(); i++) {
                        JSONObject user = users.getJSONObject(i);
                        String name = user.getString("user_name");
                        String email = user.getString("user_email");
                        String password = user.getString("user_password");

                        results.append(name);
                    }

                    results.append("\n");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        requestQueue.add(jsonObjectRequest);
    }
});
ZWis212
  • 132
  • 1
  • 13
  • what do you get when calling showUsers.php in your browser? any errors? – Jeff Jan 06 '16 at 23:17
  • Try setting the content type: http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script – Jeremy Harris Jan 06 '16 at 23:20
  • Jeff, no not getting any errors. Nothing is showing on the screen at all. Although I just noticed in the log cat i'm getting 20020-20020/practise.mysql_php_json I/System.out: org.json.JSONException: Value
    – ZWis212 Jan 06 '16 at 23:29
  • Jeremy, I did set the content type at the top in that last group of coding. Does it have to be at the top of the script page? – ZWis212 Jan 06 '16 at 23:31
  • the err you're getting in adroid is because php doesn't return a valid json. So start by making the php work (in the browser). Looks like table users is empty? – Jeff Jan 06 '16 at 23:32
  • the header is fine, only needs to be before *first* output. – Jeff Jan 06 '16 at 23:33
  • Is there any way I can run it in browser. When I open it through the server, just a blank white screen comes up. Whenever I was working on it and I had an error, it pushed the error on to the screen.\ – ZWis212 Jan 06 '16 at 23:35
  • An error file is showing up as well in the location of my php files. Says.... mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given inshowUsers.php on line 15 – ZWis212 Jan 06 '16 at 23:43
  • where is the php-script served? on your local web-server? have you error-reporting on? error_reporting(E_ALL); ini_set('display_errors', 1); – Jeff Jan 06 '16 at 23:43
  • It's on an online server through hostgator. I don't think I have error-reporting on. Just put up a website for my first time and trying to figure this all out to connect my android app with it. – ZWis212 Jan 06 '16 at 23:47
  • if it's on an online production-server error-reporting will be switched off in php-ini. with that lines error_reporting(E_ALL); ini_set('display_errors', 1); you can override that. With those errors you'll get try to debug your php-script (though it looks alright)! – Jeff Jan 06 '16 at 23:56

2 Answers2

0

You're getting errors on your php script. The first step is to turn on your error reporting, so put the code below right under your opening <?php tags:

ini_set('display_errors', 1);
error_reporting(-1);

That will show you the errors. Now reading the comments, you're query seems to be failing.

You should be checking the query to ensure it is actually successful before you try and fetch results as such.

$query = " Select * FROM users; ";

$result = mysqli_query($connect, $query);
// this checks if query failed and prints error.
if(!$result){
    die("SQL Error: ". mysqli_error($connect));
}
// will only get here if your query runs successfully.
$number_of_rows = mysqli_num_rows($result);
///... rest of your code...

Now, let us know what errors you get and if you managed to fix them. I'll update this answer as you reply.

Darren
  • 13,050
  • 4
  • 41
  • 79
0

I would rather say that probably is your query wrong. The weird thing is that you insert the users into the user_table and then somehow you select from users. So if you would actually wanted to display the users shouldn't you be selecting from at least the same table? Anyway you can modify the code like:

insertUser.php

<?php
error_reporting(E_ALL);
try{
    $handler = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
    echo $e->getMessage();
    die();
}

$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$query = $handler->query("INSERT INTO user_table(user_name, user_email, user_password) VALUES('$name','$email','$password')");

?>

Remove the mysqli connection and use PDO instead is also suggested by PHP itself.

showUsers.php

<?php
error_reporting(E_ALL);
try{
    $handler = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
    echo $e->getMessage();
    die();
}

$query = $handler->query("SELECT * FROM user_table");
$json = array();
$json = $query->fetchAll(PDO::FETCH_ASSOC);
$records['users'] = $json;
echo json_encode($records);
?>

Your result will be a JSON array called users and then you can get the data from the JAVA.

Hope it helps!!!

Kostas Drak
  • 3,222
  • 6
  • 28
  • 60