0

I'm trying to return the array of rows where the username matches the username in the database table. The JSON result just gives me the last row.

example table:

james 14 [email protected]

mah 12 [email protected]

james 23 [email protected]

result gives me:
23 [email protected]

but i want both james rows not just the last one. so both 14 [email protected] and 23 [email protected] thanks

My php code:

<?php 
    $username = $_POST["username"];

    $con = new mysqli("xx", "xx", "xx", "xx");


    // selects everything 
    $statement = mysqli_prepare($con, "SELECT * FROM `user` WHERE username = ?");
    mysqli_stmt_bind_param($statement, "s", $username);

    mysqli_stmt_execute($statement);
    // Store the result to use
    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $id, $username, $age, $email);

    // Get results returned and put in array
    $user = array();
    while (mysqli_stmt_fetch($statement)) {
        $user[age] = $age;
        $user[email] = $email;
    }

    // Send array back to phone
    print (json_encode($user));

    mysqli_stmt_close($statement);
    mysqli_close($con);

?>

3 Answers 3

1

You overwrite the array so try something like this

while (mysqli_stmt_fetch($statement)) {
        $user[] = array( 'age'=>$age, 'email'=>$email);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

user[] should be a 2 dimensional array.

In your case last element will be there in the array.

while (mysqli_stmt_fetch($statement)) {
        $user[] = array('age'=>$age,'email' =>$email);
    }

Hope this helps.

Comments

1

Your array should be empty not like [age][email] it should be empty so that array create index.

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.