Reputation: 181
I am working with mysqli in php but i'd like to know how can i retrieve data from DB with loops other than while loop?
I always use while loop to retrieve data and I've never seen anybody to use another loop to do it. is this the only way to retrieve data!!?
$select_query = "SELECT * FROM article";
if($get_from_db = $db_connection->query($select_query)){
if($get_from_db->num_rows > 0){
while($result = $get_from_db->fetch_array(MYSQLI_ASSOC)){
echo "id: " . $result['id'] . '<br>';
echo "title: " . $result['title'] . '<br>';
echo "context: " . $result['context'] . '<br>';
echo "=========================================<br>";
}
}
$get_from_db->free();
}else{
//do somthing...
}
Upvotes: 3
Views: 387
Reputation: 5203
The while loop is not used to retrieve the data, it is used to fetch it from the mysqli instance that holds the query result, and to use another loop you would need to know before hand the number of rows returned from the query result.
What I think you can do is use fetch_all
to fetch all the elements at once, and then you can use for example a foreach loop:
$rows = $get_from_db->fetch_all();
foreach ($rows as $row) {
echo "id: " . $row['id'] . '<br>';
echo "title: " . $row['title'] . '<br>';
echo "context: " . $row['context'] . '<br>';
echo "=========================================<br>";
}
Edit: You can also use for (with the same behaviour of while):
for (;$result = $get_from_db->fetch_array(MYSQLI_ASSOC);) {
//...
}
Upvotes: 3
Reputation: 714
If the data is in the form of array, you can use foreach
loop
foreach($results as $result){
echo "id: " . $result['id'] . '<br>';
echo "title: " . $result['title'] . '<br>';
echo "context: " . $result['context'] . '<br>';
echo "=========================================<br>";
}
Upvotes: 1