Reputation: 130
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?
Upvotes: 0
Views: 74
Reputation: 194
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'];
}
Upvotes: 0
Reputation: 212412
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())
Upvotes: 2