0

I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code

Code for querying

$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();

Code for display

do{
    echo result['_id'];
}while($query->fetch_assoc());

It outputs 1111 instead of 1234. Please what is wrong?

1
  • please don't use caps and coding/programming language in titles. The tags are enough. I edited your question respectively Commented Oct 26, 2015 at 22:27

2 Answers 2

2

You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed

do{
    echo $result['_id'];
}while($result = $query->fetch_assoc())
Sign up to request clarification or add additional context in comments.

6 Comments

Please, how then do I make it work. I have been outputing results that way
while($query->fetch_assoc()); <= semi-colon is a terminator. No error because that is, believe it or not a valid statement. It must be removed. while($query->fetch_assoc()){...}
oh and missing a $ for result['_id']; - result is treated as a constant.
@ITECH-PLANET - No you haven't been doing it that way..... read my answer carefully
I have checked other codes I have, it same and they are working except this one. :(
|
0

You also can use a foreach loop :

$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();

foreach($result as $data){
    echo $data['_id'];
}

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.