I have 2 files: apix.php and crud.php. I am trying to convert the fetched data from php to a jason print. The issue is that the function does not the results for me to parse in the next section of my code.

The CRUD.php:

class crud
{
    private $db;

    function __construct($DB_con)
    {
        $this->db = $DB_con;
    }   

    public function dataview_new($query)
    {
        $stmt = $this->db->prepare($query);
        $stmt->execute();

        $users = array();

        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            array_push($users, $row);
        }

        return $users;

    }

}

the APIX.php:

require_once 'crud.php';

$crud = new crud($DB_con);

$res = array('error' => false);

$action = 'read';

if(isset($_GET['action'])){
    $action = $_GET['action'];
}

if($action == 'read'){
    $query = "SELECT * FROM test";
    $crud->dataview_new($query);
    $res['users'] = $users;
}

header("Content-type: application/json");
echo json_encode($res);
die();

I am missing something obvious, because I tested the code outside the crud in the IF statement and it works fine:

if($action == 'read'){ // alternative code to the previous IF statement
    $result = $DB_con->prepare("SELECT * FROM `test`");
    $result->execute();
    $users = array();

    while($row = $result->fetch(PDO::FETCH_ASSOC)){
        array_push($users, $row);
    }

    $res['users'] = $users;
}

Solved it:

$users = $crud->dataview_new($query);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.