user1286956
user1286956

Reputation: 299

Converting OOP JSON

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

Upvotes: 0

Views: 57

Answers (1)

Dan
Dan

Reputation: 11084

You are not assigning the return value of $crud->dataview_new($query) to a variable.

You need to use an assignment:

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

Upvotes: 4

Related Questions