Home > Net >  How to access whileloop record outside the loop using array
How to access whileloop record outside the loop using array

Time:12-13

Hello i selected all records from users and returned them using a php whileloop and array, using implode i could get all the records outside the loop, what i wish to do actually is to access individual record and assign them to a variable individually to be used later in the same page.

this is what i came up with already, it works, but i don't know how to assign the recorded to individual variables, since all the records are displayed using implode

     $data = array();
        $query = "SELECT * FROM users ";
        $qeuryResult = mysqli_query($conn,$query);
        while($_row = mysqli_fetch_array($qeuryResult)){
          $data[] = $_row['first_name'];
        $data[] = $_row['email'];
        $data[]  = $_row['amount'];
           
            ?>
            <?php }?>
            <?php
            echo "<br />";
           $request = implode("<br />", $data);
          
           echo $request;

please i need assistance on how to achieve or a better way to access whileloop records outside the loop this thanks in advance

CodePudding user response:

As a result of your loop you have a $data array which you then turn into a string by gluing all its elements using implode function.

You can of course still access every individual element of $data array outside of the loop by addressing to its direct index.

For instance:

echo $data[0]['email'];

will output the email record of first (arrays are 0 based in PHP) element of your array.

CodePudding user response:

You can take a look at below code

    $data = array();
    $query = "SELECT * FROM users ";
    $qeuryResult = mysqli_query($conn,$query);
    while($_row = mysqli_fetch_array($qeuryResult)){
    array_push($data, array(
                            'first_name' => $_row['first_name'],
                            'email' => $_row['email'],
                            'amount' => $_row['amount'],
        ));
       
        }
        //print_r($data[0]['first_name']);
        echo "<pre>";
        print_r($data);
        
  •  Tags:  
  • php
  • Related