简体   繁体   English

如何正确格式化PDO结果? - 数字结果以字符串形式返回?

[英]How to properly format PDO results? - numeric results returned as string?

With relative newness to AJAX, and now just starting to learn PDO, the added level of ReSTler has me completely boggled. 随着AJAX的相对新颖,现在刚刚开始学习PDO,ReSTler的额外水平让我完全厌恶。 Modeling the below code from Restler samples, I don't know how to change the output format from what PDO is returning to what Restler and Highcharts is expecting. 从建模样本Restler下面的代码,我不知道如何改变从什么PDO 久违什么Restler和Highcharts期待的输出格式。

How do I change this code to get from the current format to the required format? 如何更改此代码以从当前格式获取所需格式? (The results will generally be 5K-10K records, if that's a factor in handling the MySQL result.) (结果通常是5K-10K记录,如果这是处理MySQL结果的一个因素。)

ReSTler API Code Snippet : ReSTler API代码段

$sql = "SELECT ....."
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    $stmt = $this->db->query($sql);
    return $stmt->fetchAll();
} catch (PDOException $e) {
    throw new RestException(502, 'Listing History: ' . $e->getMessage());
}

Current Output Format (includes unwanted column names): 当前输出格式 (包括不需要的列名称):

[
  {
    "chart_date": "1118966400000",
    "bandwidth": "10.01",
    "views": "101"
  },
  {
    "chart_date": "1119225600000",
    "bandwidth": "20.02",
    "views": "101"
  },

Desired Output Format (numeric and without column names): 期望的输出格式 (数字和列名称):

[
  [
    1118966400000,
    10.01,
    101
  ],
  [
    1119225600000,
    20.02,
    202
  ],

Edit using suggested fetch(PDO::FETCH_NUM) : 使用建议的 fetch(PDO::FETCH_NUM)编辑:

Per the answer from @Ricardo Lohmann, I tried fetch(PDO::FETCH_NUM), which DID remove the column names, but all columns returned seem to be string, not numeric, as the data actually is, so try this, giving me the right data type - is this part of PDO to unilaterally return string? 根据@Ricardo Lohmann的回答,我尝试了fetch(PDO :: FETCH_NUM),DID删除了列名,但所有返回的列似乎都是字符串,而不是数字,因为数据实际上是,所以试试这个,给我一个正确的数据类型 - 这是PDO单方面返回字符串的一部分吗?

while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
    $array[$x][0] = intval( $row[0] );
    $array[$x][1] = intval( $row[1] );
    $array[$x][2] = intval( $row[2] );
    $x++;
}
return $array;

PDO::FETCH_NUM is the way to go, though it does not mean numeric columns will remain numeric, it only means you will get an indexed array instead of an associative array (thus, it only accomplishes the omission of the column names). PDO::FETCH_NUM是要走的路,虽然它并不意味着数字列将保持数字,但它只意味着你将获得一个索引数组而不是一个关联数组(因此,它只能完成列名的省略)。

The MySQL PDO driver always returns strings for numeric columns, which is a known bug , but unfortunately, one of the many bugs that PHP devs blatantly disregard as "thank you but this is not a bug". MySQL PDO驱动程序总是返回数字列的字符串,这是一个已知的错误 ,但不幸的是,PHP开发人员公然忽视的许多错误之一是“谢谢你,但这不是一个错误”。

You can force json_encode to use actual numbers for values that look like numbers: json_encode($data, JSON_NUMERIC_CHECK) (since PHP 5.3.3). 您可以强制json_encode将实际数字用于看起来像数字的值: json_encode($data, JSON_NUMERIC_CHECK) (自PHP 5.3.3起)。

Try to set fetch mode instead of fetchall, like the following: 尝试设置获取模式而不是fetchall,如下所示:

return $stmt->fetch(PDO::FETCH_COLUMN);

You can see the reference . 你可以看到参考

The only way I found to bypass this problem (using SQLSRV driver), is to have SQL to send all datatypes as a string in an OUTPUT param. 我发现绕过这个问题(使用SQLSRV驱动程序)的唯一方法是让SQL将所有数据类型作为OUTPUT参数中的字符串发送。 And then converting all values using the correct datatype. 然后使用正确的数据类型转换所有值。 That might be heavy for big dataset. 对于大数据集来说,这可能很重要。

Even though PDO developpers says it's a driver issue (not their mistake), I never had this problem using the SQLSRV driver without PDO... 即使PDO开发人员说这是一个驱动程序问题(而不是他们的错误),我在没有PDO的情况下使用SQLSRV驱动程序从未遇到过这个问题...

You can set the next attributes as follows: 您可以按如下方式设置下一个属性:

$pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

The attribute ATTR_STRINGIFY_FETCHES let you convert numeric values to strings when fetching. 使用属性ATTR_STRINGIFY_FETCHES可以在获取时将数值转换为字符串。

I had hoped that there was a built in way to do this, thus why I performed the Google Search :v. 我原本希望有一种内置的方法可以做到这一点,这就是为什么我要执行谷歌搜索:v。

I'm building my own custom CMS application that I believe is 'Drupal-like' (I've never used Drupal but I use a custom system that is based off of Drupal). 我正在构建我自己的自定义CMS应用程序,我相信它是'Drupal-like'(我从未使用过Drupal但我使用的是基于Drupal的自定义系统)。 By this I mean I have a table in my DB that basically describes all of the fields in other tables, and when I retrieve fields from these other tables, I load up the descriptions and data type my data. 我的意思是我在我的数据库中有一个表基本上描述了其他表中的所有字段,当我从这些其他表中检索字段时,我加载了数据的描述和数据类型。

eg 例如

tablex Fields: Name, Age, Old Enough tablex字段:名称,年龄,足够

tabledescriptions : tabledescriptions

fieldname  |  datatype  |  minlength  |  parent
___________|____________|_____________|________
Name       |  String    |  5          |  tablex
Age        |  Int       |  1          |  tablex
Old Enough |  Boolean   |  1          |  tablex

So when I load data from tablex , I look in tabledescription for things where parent = 'tablex' and use a switch statement to datatype the data 所以当我从tablex加载数据时,我会在tabledescription中查找parent ='tablex'的内容并使用switch语句对数据进行数据类型化

foreach ( ... ) {
    switch ($desc->datatype) {
       case 'int': (int) $tablex->data;
            break;
    }
}
etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM