1

This is my database:

database

This is the query:

SELECT * FROM users

Now when I do this:

$query = $connection->query($_GET['query']); // SELECT * FROM users
print_r($query->fetch_assoc());

I get this as output:

Array ( [id] => 3 [username] => karel )

Why does it not output id 4 and username ccscs?

When I a while loop:

whileloop

while($row = $query->fetch_assoc()){
    print_r($row);
}

3 Answers 3

2

This is happening because you don't give any order to your query so it automatically get first record. If you want to return last record you can order by id desc as follow

SELECT * FROM users ORDER BY id DESC

If you instead need to retrieve all records you will need to loop throw your records

while($row = $query->fetch_assoc())
{
    print_r($row);
}

Based on new op info i would not fetch twice but one as follow

$fields = array();
while($row = $query->fetch_assoc())
{
    print_r($row);
    $fields[] = $row;
}
Sign up to request clarification or add additional context in comments.

4 Comments

This would return the last record, but I think the OP wants to get all rows.
That's why i placed both solution
Use second solution then, loop throw all records.
Don't fetch result twice, just do both operation in the same loop.
2

fetch_assoc() retrieves a single row from a result set. See here.

mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row as an associative array

You should use something like this :

while($row = $query->fetch_assoc()){
   print_r($row);
}

Comments

2

That's because fetch_assoc() just fetches one row.

To get each row you can do it like this:

while($row = $query->fetch_assoc()){
   print_r($row);
}

5 Comments

Still one line: while($fetch = $query->fetch_assoc()) { print_r($fetch); }
What do you mean? Could you please show us the output. If you mean that every row has a single line is normal.
@user3144435 That's because of this for loop you placed before. It already retrieved the first line and the while loop just gets the rest. Remove it and it should work.
Do you mean the foreach loop? Thats to get the field names, when I remove that it works but now I could not get the fieldnames anymore.
You will need to write a own query for get the field names, or you could get the names in the first iteration of the while.

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.