Denominator
Denominator

Reputation: 216

Fetch rows from database table android

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);

?>

Upvotes: 0

Views: 79

Answers (3)

Santosh Patel
Santosh Patel

Reputation: 539

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

Upvotes: 1

Subin Chalil
Subin Chalil

Reputation: 3660

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.

Upvotes: 1

Mazaka
Mazaka

Reputation: 634

You overwrite the array so try something like this

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

Upvotes: 1

Related Questions