0

I am not a php pro and have already explored different online search forums but could not find any suitable answer and that's why posting my question here.

Function One: Runs a query to database and define variables in foreach loop as follows:

function myFunction(){
 $dbinfo = get_db_info();
 $users = $dbinfo->get_results("
    SELECT 
       Email,
       ID,
       Name,
       Address
        FROM Database_table
        WHERE ID = 5
    ");
    
    if($users) {
        $output = '';
        foreach($users as $user) {
            $ID = $user->ID;
            $dname = $user->Name;
            $email = $user->Email;
            $address = $user->Address;
        }else{
            $output .= 'No user found';
        }

    }//endif
    return $output;
}

Function two: Now I want to get the values of those variables in another function as follows:

function dislayData(){

    $values = myFunction();
    echo $values=>$email;

}

But it does not work. It seems I may need to wrap variables in the foreach loop into an array. I don't understand how to do that.

Any help here would be highly appreciated.

Thanks in advance.

Bakar

1
  • what is echo $values=>$email;? Commented Oct 6, 2020 at 18:37

2 Answers 2

2
function myFunction(){
    $dbinfo = get_db_info();
    $users = $dbinfo->get_results("SELECT Email, ID, Name, Address
                                    FROM Database_table
                                    WHERE ID = 5");
    
    if($users) {
        $arrOutput = [];
        foreach($users as $user) {
            $arrOutput[]    =   [
                'ID'    =>  $user->ID,
                'dname' =>  $user->Name,
                'email' =>  $user->Email,
                'address'   =>  $user->Address
            ];
        }
        return $arrOutput;
    }
    else{
        return false;
    }
}

function dislayData(){

    $values = myFunction();

    if($values !== false){
        foreach($values as $user){
            // Now you can access property of each uesr
            echo $user['email'];
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I think you forgot to store the users data in the variable "output".

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.