PHP question: Problem converting pdo column value to string
P粉403804844
P粉403804844 2024-04-03 00:18:38
0
1
567

Essentially, I'm using pdo to run the following query and format the results into JSON. The problem is that I need column2 to always appear as a string in JSON, even if the value is a number, without reformatting the other column values, so I'm trying to do a for loop to convert using strvalue.

$stmt = $pdoConnect->prepare('

    SELECT column1, column2, column3 from table1 where column1 = "tree"
');

$stmt->execute([]);


$row = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($row as $rowvalue) {
    strval($rowvalue["column2"]);
}
    
echo json_encode($row);
?>

Current JSON response:

[
  {
    "column1": "tree",
    "column2": 29012,
    "column3": "foggy"
  },
  {
    "column1": "tree",
    "column2": 00930239,
    "column3": "sunny"
  },
   {
    "column1": "tree",
    "column2": 203943,
    "column3": "rainy"
   }
  ]

Ideal JSON response:

[
  {
    "column1": "tree",
    "column2": "29012",
    "column3": "foggy"
  },
  {
    "column1": "tree",
    "column2": "00930239",
    "column3": "sunny"
  },
   {
    "column1": "tree",
    "column2": "203943",
    "column3": "rainy"
   }
  ]

P粉403804844
P粉403804844

reply all(1)
P粉979586159

You can try it, ATTR_STRINGIFY_FETCHES

$pdoConnect->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);

Reference:https://www.php.net/manual/en /pdo.setattribute.php

phpfiddle

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template