3

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...
}
3
  • Possible duplicate of Use mysql_fetch_array() with foreach() instead of while() Commented Aug 27, 2019 at 11:37
  • It's not the only way but it's the simplest. Is there a problem or are you just curious? Commented Aug 27, 2019 at 11:46
  • i'm just curious! Commented Aug 27, 2019 at 11:53

2 Answers 2

3

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);) {
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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>";
 }

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.