Home  >  Q&A  >  body text

PHP question: Problem converting pdo column value to string

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粉403804844P粉403804844223 days ago496

reply all(1)I'll reply

  • P粉979586159

    P粉9795861592024-04-03 20:33:20

    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

    reply
    0
  • Cancelreply