douben7260 2016-02-09 10:14
浏览 174

数字转换为PHP和PDO到MYSQL的字符串

Iam using PHP (5.6.8) to act as the middle tier between a MySQL database and returning the results in JSON format.

We are using the PHP extension (PDO) to do the database interaction, but have noticed that all numeric values get returned as a string. The database itself is running on a Linux installation, but during development, both the client and middle tier are running on Windows.

I set the connection parameter "ATTR_STRINGIFY_FETCHES" to false but that made no difference. e.g. $dbConnection->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);

This is the PHP function that I am using to retrieve data and it is tied to the RESTful interface.

function getAllObjects() 
{
    $sql = "SELECT * FROM Tbl_Objects ORDER BY 1";
    try {
       $db = getDB();
       $stmt = $db->query($sql);  
       $objects = $stmt->fetchAll(PDO::FETCH_OBJ);
       $db = null;
       echo json_encode($objects);
    } catch(PDOException $e) {
       echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

I also tried "mysqli" but I get the same results in that the numeric values are all converted to Strings. If I use the "cast_query_results($rs)" function on the net, I do get numeric converted correctly, but it seems to me that this is rather a fudge, rather than a solution.

Any ideas on how to get this to work natively please?

  • 写回答

3条回答 默认 最新

  • dongliufa6380 2016-02-09 10:20
    关注

    Alternatively you can force json_encode() to convert string numbers to integers with:

    json_encode($objects, JSON_NUMERIC_CHECK);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?