简体   繁体   English

PDO在PHP5.4中将整数列作为String返回

[英]PDO returns integer columns as String in PHP5.4

First of all, I am aware that there are various similar questions on SO such as this and this . 首先,据我所知,有作为SO等各种类似的问题这个这个 However, when I fetch values from a table, integers are always fetched as string. 但是,当我从表中获取值时,整数总是被提取为字符串。

I am using PHP5.4 (5.4.16-1~dotdeb.1) and MYSQL5.5 (5.5.31+dfsg-0+wheezy1). 我使用PHP5.4(5.4.16-1~dotdeb.1)和MYSQL5.5(5.5.31 + dfsg-0 + wheezy1)。 It is written here that MySQL Native Driver is enabled by default in PHP5.4.0. 这里写的是PHP5.4.0中默认启用了MySQL Native Driver。 But I still get string values. 但我仍然得到字符串值。

I initialize a PDO object as follows. 我按如下方式初始化PDO对象。

try {
        $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';

        $db = new PDO($dsn,DB_USER,DB_PASS);

        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    } catch (PDOException $e) {
        header('HTTP/1.1 500');
        exit;
    } catch (Exception $e) {
        header('HTTP/1.1 500');
        exit;
    }

When I insert, I tried to use execute(array(...)) format and also used bindValue(...,PDO::PARAM_INT) , but they did not make a difference. 当我插入时,我尝试使用execute(array(...))格式并且还使用了bindValue(...,PDO::PARAM_INT) ,但它们并没有什么区别。

For example, here is how I insert a new row. 例如,以下是我插入新行的方法。

public function insertList ($db,$account_id,$list_name) {
    $sql = $db->prepare('INSERT INTO lists VALUES (?,?,?,?,?)');

    try {
        // $sql->execute(array($list_name,0,0,0,$account_id));

        $sql->bindValue(1,$list_name,PDO::PARAM_STR);
        $sql->bindValue(2,0,PDO::PARAM_INT);
        $sql->bindValue(3,0,PDO::PARAM_INT);
        $sql->bindValue(4,0,PDO::PARAM_INT);
        $sql->bindValue(5,$account_id,PDO::PARAM_INT);
        $sql->execute();
    } catch (PDOException $e) {
        header('HTTP/1.1 500');
        exit;
    } catch (Exception $e) {
        header('HTTP/1.1 500');
        exit;
    }
}

Here is how I fetch rows from a table 以下是我从表中获取行的方法

public function fetchLists ($db,$account_id) {
    $sql = $db->prepare('SELECT * FROM lists WHERE account_id=?');

    try {
        $sql->execute(array($account_id));

        $result = $sql->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        header('HTTP/1.1 500');
        exit;
    } catch (Exception $e) {
        header('HTTP/1.1 500');
        exit;
    }

    return $result;
}

This did not occur when I tested on XAMPP for Linux 1.8.1 which uses PHP5.4.7. 当我在使用PHP5.4.7的XAMPP for Linux 1.8.1上进行测试时,没有发生这种情况。 I currently use nginx instead of Apache. 我目前使用的是nginx而不是Apache。

What is wrong? 怎么了?

要从带有PDO的mysql获取具有相应类型的整数和浮点数,您需要关闭基于mysqlnd的PDO-mysql和仿真模式。

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

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