Convert PDO recordset to JSON in PHP [duplicate] - php

This question already has answers here:
How to create a JSON object
(5 answers)
Closed 2 years ago.
Im using PHP and I need a way to convert an entire recordset to a JSON string.
While searching Stack Overflow I found this solution that works:
function recordSetToJson($mysql_result) {
$rs = array();
while($rs[] = mysql_fetch_assoc($mysql_result)) {
// you donĀ“t really need to do anything here.
}
return json_encode($rs);
}
The problem with this code is that I found that the function mysql_fetch_assoc() is deprecated in PHP 5.5.0. Another thing is that im using PDO to connect to my database.
Given the circunstances above, what would be the best solution to convert a PDO recordset to JSON? I want it to work at later versions of PHP too.

The solution is simple.
Considering that the variable $stmt is your PDO recordset, you can convert it to JSON like this:
json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
For more info about the functions used in this piece of code:
http://www.php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/pdostatement.fetchall.php

You should use something like that
somewhere previously
$stmt = $pdo->prepare("SELECT * FROM fruit WHERE name = ?");
$stmt->execute(array("Apple"));
....
function recordSetToJson($stmt) {
$json_result = array();
while($tmp = $stmt->fetch() ) {
$json_result[] = $tmp;
}
return json_encode($json_result);
}
But final solution will be totally depends form too many factors.

Related

Sort PHP object with in the order of elements an array has [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 3 months ago.
There is scenaria when I fetch results from mysql table using PHP. The results have a column named as status. That column has multiple values like follow up, won and lost. I want to show the results in this order using PHP
Follow up
Won
Lost
How can I achieve this?
I am looking at PHP sort functions but not getting the result I want. So need a solution to get the results in the same way I mentioned.
This is the trick for the above
$sortvalue = 'Follow up';
$result = array_filter($results, function ($item) use ($sortvalue) {
if(stripos($item['status'], $sortvalue) !== false) {
return true;
}
return false;
});
var_dump($result);

PHP: fetch_assoc() into array causing null values [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 3 years ago.
I'm trying to fetch data from a MariaDB database of festivals and respective locations. When running:
while($row = $sth->fetch_assoc()){}
and iterating over $row while outputting the values, I get data as it is in the database.
However, when storing each row like so:
while($row = $sth->fetch_assoc()){
$results[] = $row;
}
And echoing the results as JSON (echo json_encode($results);)
I get this:
{"id":"0","name":null,"village":"0","startDate":"2019-01-16",
"endDate":"2019-01-23","message":null}
This is for an existing Linux server, which I do not manage (I'm using CPanel). PHP version is 5.4 and MariaDB 10.1.37.
So far, a lot of code samples on Stack Overflow and other websites are using
$results[] = $row;
for storing the results.
I'm returning to PHP after 3 years of Swift only programming... So I suspect this could be a simple issue to solve...
Thanks!
May be I'm bit too late for answering this question, but it may help someone stuck with this issue. Recently I faced a similar issue and it took me 3 days to understand that it is an issue with the utf-8 characters. Data stored in database are perfectly fine. But when it comes to return it via json_encode(), it shows no data at all as json_encode only supports utf-8 data(reference).
For your case the following method should work-
foreach ($results as &$r) {
$r['name'] = utf8_encode($r['name']);
//same for all other items
}

Defining a mySql result as a variable for a while loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am wondering if this is possible. I know this is hardly practical...I did though, run into a case where this might come in handy.
Take this example, straight forward.
while( $row = $qry->fetch(PDO::FETCH_ASSOC) ){}
Now, can something like this be done?
$newVar = '$row = $qry->fetch(PDO::FETCH_ASSOC)';
while($newVar){}
I have tried many ways but to no avail.
My while loops print out a lot of data and depending on the type of query/connection (mySql, mySqli, or PDO) would depend on what statement goes into the while loop.
This is somewhat my fallback idea if prepared statements are not supported.
If the function to fetch a row is different, you may be able to use closures depending on the PHP version you are using. To use closures, you would want to define a function that knows how to fetch a row, then you can pass it to your while loop. For example, here are closures for PDO and MySQL:
$pdo_fetch = function() use ($qry)
{
return $qry->fetch(PDO::FETCH_ASSOC);
}
$mysql_fetch = function() use ($result)
{
return mysql_fetch_assoc($result);
}
These closures can come from anywhere, then passed into your while loop:
if($pdo)
{
$fetch = $pdo_fetch;
}
else
{
$fetch = $mysql_fetch;
}
while($row = $fetch()) { }

Is there a way to get just one element from array that is returned as a function? [duplicate]

This question already has answers here:
Accessing an array element when returning from a function
(3 answers)
Closed 9 years ago.
Say I have a function/method that returns an array, let's call it ArrayReturner(). But I only want the first element, [0]. Right now I'm doing something like...
$arrayReturned = ArrayReturner();
$varIWant = $arrayReturned[0];
Is there a way to do that in one line without the need for the temporary $arrayReturned array?
Try:
$arrayReturned = reset(ArrayReturner());
Depends on PHP's version you use.
If you're using PHP < 5.4, then you cannot get that, like ArrayReturner()[0]. That's only possible in PHP >= 5.4.
If you want your code to be portable, that would work with old and new versions, then you'd better stick with that code:
$arrayReturned = ArrayReturner();
$varIWant = $arrayReturned[0];

add math operators in function php [duplicate]

This question already has answers here:
How to mathematically evaluate a string like "2-1" to produce "1"?
(9 answers)
Closed 9 years ago.
I'm kinda new to this but I was wondering if it is possible to add some dynamic calculation into a function as a parameter.
The thing is inside my function I am formatting stuff in a consistent way but each time I want to add a certain different calculation into the parameter.
<?php
function dynamicCalculator($calculation){
$result = $calculation;
//some formatting
return $result;
}
echo dynamicCalculator('(3x5)+1');
This doesn't work of course but if anyone has an idea how this could work I would love to hear it.
What you are looking for is the eval function.
eval('$result = (3*5)+1');
But beware to make sure you're not passing possibly harmful code to that function.
Your looking for RPN (Reverse Polish Notation)
Here is one example
http://pear.php.net/package/Math_RPN/
which would allow you to use
$expression = "(2^3)+sin(30)-(!4)+(3/4)";
$rpn = new Math_Rpn(); echo $rpn->calculate($expression,'deg',false);
And not have to use Eval
Use eval. eval("10+2") should return 12. Be careful though, you can also run PHP code with eval.
Someone else had a similar question on StackOverflow.
You could use this:
function dynamicCalculator($calculation) {
$result = eval($calculation);
return $result;
}

Categories