1

Good evening everyone, until a few days ago I had never used PHP or JSON and I am finding trouble getting multiple rows from phpmyadmin to Java using JSON. I have manged to write the below code however this only gets the last row.

I took a look at this post (how to encode multiple rows from mysql into json using php) and had a go but have had no luck..

    <?php

    $user = 'root';
    $pass = '';
    $db = 'uopuser';

    $con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');


    $statement = mysqli_prepare($con, 'SELECT * FROM society');
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $society_id, $name, $email, $description);

    $society = array();

    while(mysqli_stmt_fetch($statement)){
        $society['society_id'] = $society_id;
        $society['name'] = $name;
        $society['email'] = $email;
        $society['description'] = $description;
    }

    echo json_encode($society);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

Thank you in advance!

3
  • 1
    Q: Where does "Java" come in? Your PHP 1) Executes on the server, 2) the server talks to the database, and 3) your "echo" presumably writes some valid JSON to the browser. Q: Where/how exactly are you using "Java"???? PS: Your "while" loop is wrong - each iteration overwrites the previous value. You might want to move "echo" inside the loop... Commented Mar 4, 2016 at 23:49
  • @paulsm4 I will be using this data to populate a ListView for an Android application. At the moment I just need to get my PHP/JSON correct. I'll test your suggestion, thanks for pointing that out to me. Commented Mar 4, 2016 at 23:55
  • How did I not see this! Thank you very much guys. Commented Mar 5, 2016 at 0:02

1 Answer 1

0

Just needed to put my echo inside the while loop

while(mysqli_stmt_fetch($statement)){
            $society['society_id'] = $society_id;
            $society['name'] = $name;
            $society['email'] = $email;
            $society['description'] = $description;
        }

        echo json_encode($society);

to

while(mysqli_stmt_fetch($statement)){
        $society['society_id'] = $society_id;
        $society['name'] = $name;
        $society['email'] = $email;
        $society['description'] = $description;
        echo json_encode($society);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.