0

i have a small problem with my php code.

i've created a class for Clients, to return me a list with all clients. The problem is when i call the function from outsite, it dont show me the clietsList.

<?php 

$returnData = array();

class Clients
{
     public function readAll(){
        $query = "SELECT * FROM clients";
        $result = $this->con->query($query);
        if ($result->num_rows > 0){
            while ($row = $result->fetch_assoc()){
                $returnData['clientsList'][] = $row;
            }
            return $returnData;
        }
        else{
            echo "No found records";
        }
    }
}


if ($auth->isAuth()){
    $returnData['message'] = "you are loggedin, so is ok";
    $clientsObj = new Clients();
    $clientsObj->readAll();
}

echo json_encode($returnData);
?>

and the result is like that, but without clietslist

{
  "message": "you are loggedin, so is ok"
}

Where im doing wrong? Thanks for your answer. i want to learn php, im begginer. thanks in advance.

1
  • 1
    Read up on Variable scope. $returnData outside of your class is different than inside your class. Commented Apr 1, 2021 at 5:50

2 Answers 2

1

You need to get return value of function in a variable:

$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$returnData['clients'] =    $clientsObj->readAll();
Sign up to request clarification or add additional context in comments.

Comments

1

$returnData on you first line will not be same as $returnData in your function. $returnData in readAll function will be a new variable.

I suggest you to read about variable scope in php. https://www.php.net/manual/en/language.variables.scope.php

Now, You will need to store returned value from function in a variable like this

$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientListArray =  $clientsObj->readAll(); //store returned value in a variable
$returnData['clientsList'] = $clientListArray['clientsList'];

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.