convert mysql data to json

As I understand the problem that you are facing is how to return rows from the class methods, when it should only return true on success and false on fail.

You got something like that:

<?php
    class user{
    
        ...
    
        public function fetchUserData($username)
            {
                try
                {
                $stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
                $stmt->execute(array(':username' => $username));
                $userRows = $stmt->fetch(PDO::FETCH_ASSOC);
                if($stmt->rowCount() > 0)
                {
                    return true;
                }
                else
                {
                    return false;   
                }
                
                }
                catch(PDOException $ex)
                {
                echo $ex->getMessage();
                }
            }
        
        ...
    
        }
?>

You need to add a public property like $userRows to it and assign that property with your method:

class user{   
    public $userRows; // added here

    ...

    public function fetchUserData($username)
        {
            try
            {
            $stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
            $stmt->execute(array(':username' => $username));
            $this->userRows = $stmt->fetch(PDO::FETCH_ASSOC); // changed here

And after that you can:

<?php

    ...

    if($user->fetchUserData($username)){
        echo json_encode($user->userRows);
    }else{
        echo "error occured";
    }

Hopefully it helped.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top