The json result of my php file contains ints but I need all the values as Strings

105
December 24, 2017, at 11:34 AM

my json result from the mysqlquery in the php-file looks something like this: [{"ID":1,"comment":"Hello"},{"ID":2,"comment":"SecondHello"}] For my purpose I need the IDs also as a String. I cannot/do not want to change the datatype in the database. What do I have to change in my php file or in the Sql query to get the ID as a String.

 <?php
     $host = '';
     $db   = '';
     $user = '';
     $pass = '';
     $charset = 'utf8mb4';
     $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
     $opt = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
     ];
     $pdo = new PDO($dsn, $user, $pass, $opt);

     $sql= SELECT * FROM orders
     $resultArray = array();
     $tempArray = array();
     foreach ($pdo->query($sql) as $row) {
        $tempArray = $row;
        array_push($resultArray, $tempArray);
      }
     echo json_encode($resultArray);
    ?>`
Answer 1

You can make sure that each row as you add it in is converted using strval...

 foreach ($pdo->query($sql) as $row) {
    $tempArray = array_map('strval', $row);    // Convert all columns to strings
    array_push($resultArray, $tempArray);
  }

Adds an overhead as this is applied to all columns, but it saves individual column by column processing (especially when the SQL changes)

Answer 2

You can use array_map to crawl your array and cast each element to string with strval

foreach ($pdo->query($sql) as $row) {
    $tempArray = array_map('strval', $row);
    array_push($resultArray, $tempArray);
}
Answer 3

what about this piece of code

$resultArray = array();
$tempArray = array();
foreach ($pdo->query($sql) as $row) {
    $fields = json_decode($row["jsonFieldName"],1);//decode your json string
    foreach($fields as $key=>$field){// read each object..
      $field["ID"] = strval($field["ID"]);// change the id property to str
      $fields[$key] = $field;// update decoded array
    }
    $row["jsonFieldName"] = json_encode($fields);//encode array and update value
    array_push($row, $row);

}

It may help you, but it is not a good way to do.

READ ALSO
Laradock can&#39;t install nginx or mysql

Laradock can't install nginx or mysql

I am using Laradock, but after executing this command:

260
Access the data using $_POST

Access the data using $_POST

Let's say I have $question = 4;I cannot access: $_POST[$question] although when I write $_POST[4] I can access this value

172
Query a table and sum datas depending their status

Query a table and sum datas depending their status

I have the following table structure:

158