How to convert a PDOStatement to JSON and print it?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















How to convert a PDOStatement to JSON and print it?
I am implementing the following function in PHP with which I want to return an array depending on an id, but when I convert the array to json and print it, the result does not appear.



public static function getAllDebtorsByUser(int $id) : array {
$query = "SELECT id_debtor Id, name_debtor Name, address_debtor Address, phone_debtor Phone from debtors where user_debtor = :i;";
$sth = Connection::select($query, ["i" => $id]); //return a PDOStatement
if($sth->rowCount() > 0) {
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$debtors = $row;
}
return $debtors;
} else
return ;
}


I used the following code to convert from array to JSON. It does not mark me errors, but it does not show me the result unless I want to show a single column instead of 3.



Example



Code to print:



echo json_encode (Debtor::getAllDebtorsByUser (1)); // The function is inside a class called Debtor


Query:



SELECT id_debtor Id from debtors where user_debtor =: i;


Result:



[
    {
     "Id": "1"
    },
    {
     "Id": "2"
    }
]


Having the 3 columns I need and using the PHP function * print_r * shows me the correct result, but what I need is for the JSON to be seen.



Example:



Code to print:



print_r (Debtor::getAllDebtorsByUser (1));


Query:



SELECT id_debtor Id, name_debtor Name, address_debtor Address, phone_debtor Phone from debtors where user_debtor =: i;


Result:



Array
    (
        [0] => Array
            (
                [Id] => 1
                [Name] => Debtor 1
                [Address] => Dir 1
                [Phone] => Tel 1
            )
    
        [1] => Array
            (
                [Id] => 2
                [Name] => Debtor 2
                [Address] => Dir 2
                [Phone] => Tel 2
            )
    
    )


So using echo json_encode () to print does not work for me unless the query has only one column.



It also does not work indicating depth to json_encode ()



** Software versions **



PHP: 7.2.12



MySQL: 5.7.24



XAMPP: 3.2.2



SO: Windows 10










share|improve this question


















  • 1





    You likely made a mistake in your observations or function usage. Any array that print_r outputs would easily pass json_encode alike. Store the result in a variable, then run print_r and echo json_enc on that. Showcase these results instead.

    – mario
    Nov 24 '18 at 20:58











  • What is Connection::select? It doesn't seem like you're using raw PDO. It looks like the values for Name, Address and Phone are not plain objects or arrays so PHP doesn't know how to serialize them, that's why you get only the Id field.

    – Stefan
    Nov 24 '18 at 21:00






  • 1





    What do you mean json_encode() "does not work?" What happens when you try to encode the results of the function? What does json_last_error_msg() say?

    – miken32
    Nov 24 '18 at 21:39











  • Note: you can greatly simplify your code (i.e. replacing the if and while) by using fetchAll().

    – Dormilich
    Nov 27 '18 at 9:16


















0















How to convert a PDOStatement to JSON and print it?
I am implementing the following function in PHP with which I want to return an array depending on an id, but when I convert the array to json and print it, the result does not appear.



public static function getAllDebtorsByUser(int $id) : array {
$query = "SELECT id_debtor Id, name_debtor Name, address_debtor Address, phone_debtor Phone from debtors where user_debtor = :i;";
$sth = Connection::select($query, ["i" => $id]); //return a PDOStatement
if($sth->rowCount() > 0) {
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$debtors = $row;
}
return $debtors;
} else
return ;
}


I used the following code to convert from array to JSON. It does not mark me errors, but it does not show me the result unless I want to show a single column instead of 3.



Example



Code to print:



echo json_encode (Debtor::getAllDebtorsByUser (1)); // The function is inside a class called Debtor


Query:



SELECT id_debtor Id from debtors where user_debtor =: i;


Result:



[
    {
     "Id": "1"
    },
    {
     "Id": "2"
    }
]


Having the 3 columns I need and using the PHP function * print_r * shows me the correct result, but what I need is for the JSON to be seen.



Example:



Code to print:



print_r (Debtor::getAllDebtorsByUser (1));


Query:



SELECT id_debtor Id, name_debtor Name, address_debtor Address, phone_debtor Phone from debtors where user_debtor =: i;


Result:



Array
    (
        [0] => Array
            (
                [Id] => 1
                [Name] => Debtor 1
                [Address] => Dir 1
                [Phone] => Tel 1
            )
    
        [1] => Array
            (
                [Id] => 2
                [Name] => Debtor 2
                [Address] => Dir 2
                [Phone] => Tel 2
            )
    
    )


So using echo json_encode () to print does not work for me unless the query has only one column.



It also does not work indicating depth to json_encode ()



** Software versions **



PHP: 7.2.12



MySQL: 5.7.24



XAMPP: 3.2.2



SO: Windows 10










share|improve this question


















  • 1





    You likely made a mistake in your observations or function usage. Any array that print_r outputs would easily pass json_encode alike. Store the result in a variable, then run print_r and echo json_enc on that. Showcase these results instead.

    – mario
    Nov 24 '18 at 20:58











  • What is Connection::select? It doesn't seem like you're using raw PDO. It looks like the values for Name, Address and Phone are not plain objects or arrays so PHP doesn't know how to serialize them, that's why you get only the Id field.

    – Stefan
    Nov 24 '18 at 21:00






  • 1





    What do you mean json_encode() "does not work?" What happens when you try to encode the results of the function? What does json_last_error_msg() say?

    – miken32
    Nov 24 '18 at 21:39











  • Note: you can greatly simplify your code (i.e. replacing the if and while) by using fetchAll().

    – Dormilich
    Nov 27 '18 at 9:16














0












0








0








How to convert a PDOStatement to JSON and print it?
I am implementing the following function in PHP with which I want to return an array depending on an id, but when I convert the array to json and print it, the result does not appear.



public static function getAllDebtorsByUser(int $id) : array {
$query = "SELECT id_debtor Id, name_debtor Name, address_debtor Address, phone_debtor Phone from debtors where user_debtor = :i;";
$sth = Connection::select($query, ["i" => $id]); //return a PDOStatement
if($sth->rowCount() > 0) {
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$debtors = $row;
}
return $debtors;
} else
return ;
}


I used the following code to convert from array to JSON. It does not mark me errors, but it does not show me the result unless I want to show a single column instead of 3.



Example



Code to print:



echo json_encode (Debtor::getAllDebtorsByUser (1)); // The function is inside a class called Debtor


Query:



SELECT id_debtor Id from debtors where user_debtor =: i;


Result:



[
    {
     "Id": "1"
    },
    {
     "Id": "2"
    }
]


Having the 3 columns I need and using the PHP function * print_r * shows me the correct result, but what I need is for the JSON to be seen.



Example:



Code to print:



print_r (Debtor::getAllDebtorsByUser (1));


Query:



SELECT id_debtor Id, name_debtor Name, address_debtor Address, phone_debtor Phone from debtors where user_debtor =: i;


Result:



Array
    (
        [0] => Array
            (
                [Id] => 1
                [Name] => Debtor 1
                [Address] => Dir 1
                [Phone] => Tel 1
            )
    
        [1] => Array
            (
                [Id] => 2
                [Name] => Debtor 2
                [Address] => Dir 2
                [Phone] => Tel 2
            )
    
    )


So using echo json_encode () to print does not work for me unless the query has only one column.



It also does not work indicating depth to json_encode ()



** Software versions **



PHP: 7.2.12



MySQL: 5.7.24



XAMPP: 3.2.2



SO: Windows 10










share|improve this question














How to convert a PDOStatement to JSON and print it?
I am implementing the following function in PHP with which I want to return an array depending on an id, but when I convert the array to json and print it, the result does not appear.



public static function getAllDebtorsByUser(int $id) : array {
$query = "SELECT id_debtor Id, name_debtor Name, address_debtor Address, phone_debtor Phone from debtors where user_debtor = :i;";
$sth = Connection::select($query, ["i" => $id]); //return a PDOStatement
if($sth->rowCount() > 0) {
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$debtors = $row;
}
return $debtors;
} else
return ;
}


I used the following code to convert from array to JSON. It does not mark me errors, but it does not show me the result unless I want to show a single column instead of 3.



Example



Code to print:



echo json_encode (Debtor::getAllDebtorsByUser (1)); // The function is inside a class called Debtor


Query:



SELECT id_debtor Id from debtors where user_debtor =: i;


Result:



[
    {
     "Id": "1"
    },
    {
     "Id": "2"
    }
]


Having the 3 columns I need and using the PHP function * print_r * shows me the correct result, but what I need is for the JSON to be seen.



Example:



Code to print:



print_r (Debtor::getAllDebtorsByUser (1));


Query:



SELECT id_debtor Id, name_debtor Name, address_debtor Address, phone_debtor Phone from debtors where user_debtor =: i;


Result:



Array
    (
        [0] => Array
            (
                [Id] => 1
                [Name] => Debtor 1
                [Address] => Dir 1
                [Phone] => Tel 1
            )
    
        [1] => Array
            (
                [Id] => 2
                [Name] => Debtor 2
                [Address] => Dir 2
                [Phone] => Tel 2
            )
    
    )


So using echo json_encode () to print does not work for me unless the query has only one column.



It also does not work indicating depth to json_encode ()



** Software versions **



PHP: 7.2.12



MySQL: 5.7.24



XAMPP: 3.2.2



SO: Windows 10







php mysql json pdo






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 20:51









Alejandro ArelisAlejandro Arelis

12




12








  • 1





    You likely made a mistake in your observations or function usage. Any array that print_r outputs would easily pass json_encode alike. Store the result in a variable, then run print_r and echo json_enc on that. Showcase these results instead.

    – mario
    Nov 24 '18 at 20:58











  • What is Connection::select? It doesn't seem like you're using raw PDO. It looks like the values for Name, Address and Phone are not plain objects or arrays so PHP doesn't know how to serialize them, that's why you get only the Id field.

    – Stefan
    Nov 24 '18 at 21:00






  • 1





    What do you mean json_encode() "does not work?" What happens when you try to encode the results of the function? What does json_last_error_msg() say?

    – miken32
    Nov 24 '18 at 21:39











  • Note: you can greatly simplify your code (i.e. replacing the if and while) by using fetchAll().

    – Dormilich
    Nov 27 '18 at 9:16














  • 1





    You likely made a mistake in your observations or function usage. Any array that print_r outputs would easily pass json_encode alike. Store the result in a variable, then run print_r and echo json_enc on that. Showcase these results instead.

    – mario
    Nov 24 '18 at 20:58











  • What is Connection::select? It doesn't seem like you're using raw PDO. It looks like the values for Name, Address and Phone are not plain objects or arrays so PHP doesn't know how to serialize them, that's why you get only the Id field.

    – Stefan
    Nov 24 '18 at 21:00






  • 1





    What do you mean json_encode() "does not work?" What happens when you try to encode the results of the function? What does json_last_error_msg() say?

    – miken32
    Nov 24 '18 at 21:39











  • Note: you can greatly simplify your code (i.e. replacing the if and while) by using fetchAll().

    – Dormilich
    Nov 27 '18 at 9:16








1




1





You likely made a mistake in your observations or function usage. Any array that print_r outputs would easily pass json_encode alike. Store the result in a variable, then run print_r and echo json_enc on that. Showcase these results instead.

– mario
Nov 24 '18 at 20:58





You likely made a mistake in your observations or function usage. Any array that print_r outputs would easily pass json_encode alike. Store the result in a variable, then run print_r and echo json_enc on that. Showcase these results instead.

– mario
Nov 24 '18 at 20:58













What is Connection::select? It doesn't seem like you're using raw PDO. It looks like the values for Name, Address and Phone are not plain objects or arrays so PHP doesn't know how to serialize them, that's why you get only the Id field.

– Stefan
Nov 24 '18 at 21:00





What is Connection::select? It doesn't seem like you're using raw PDO. It looks like the values for Name, Address and Phone are not plain objects or arrays so PHP doesn't know how to serialize them, that's why you get only the Id field.

– Stefan
Nov 24 '18 at 21:00




1




1





What do you mean json_encode() "does not work?" What happens when you try to encode the results of the function? What does json_last_error_msg() say?

– miken32
Nov 24 '18 at 21:39





What do you mean json_encode() "does not work?" What happens when you try to encode the results of the function? What does json_last_error_msg() say?

– miken32
Nov 24 '18 at 21:39













Note: you can greatly simplify your code (i.e. replacing the if and while) by using fetchAll().

– Dormilich
Nov 27 '18 at 9:16





Note: you can greatly simplify your code (i.e. replacing the if and while) by using fetchAll().

– Dormilich
Nov 27 '18 at 9:16












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53462254%2fhow-to-convert-a-pdostatement-to-json-and-print-it%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53462254%2fhow-to-convert-a-pdostatement-to-json-and-print-it%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()