PHP MySQL PDO: how to preserve leading zeros of zerofill int columns

后端 未结 2 1496
余生分开走
余生分开走 2021-02-13 04:56

I\'ve hit one more bump in the road of migrating from the old mysql_*() functions to the new PDO class: I have a the following table:

CREATE TABLE `         


        
相关标签:
2条回答
  • 2021-02-13 05:03

    I'd write small routine to patch the PDO output to suit the requirements, and try to make the least amout of changes to the coding.

    $results = pdoFix($SqlResult->fetchAll(PDO::FETCH_BOTH))

    function pdoFix($results) {
        foreach ($results as &$row) { // note the "&"
          $row[0] = sprintf("%'04s",$row[0]); // zerofill '0'
          $row['id'] = sprintf("%'04s",$row['id']); // zerofill 'id'
        }
        unset($row); // break the reference with the last element
        return $results;
    }
    

    Note: The other answers are just as good, pick one that you are most comfortable with.

    0 讨论(0)
  • 2021-02-13 05:22

    you may use LPAD?

    try this: SELECT *, LPAD( Id, 3, '0') AS zero_Fill_Id FROM test

    should change 3 according to int size: maybe 4 for this situation?

    Update:

    I don't think change int to decimal to be good practice, why I'll not go deeper at this, you can search on that subject.

    I think you use mysqlnd driver, what I've found about it (check if enabled How to know if MySQLnd is the active driver?):

    Advantages of using mysqlnd for PDO

    mysqlnd returns native data types when using Server-side Prepared Statements, for example an INT column is returned as an integer variable not as a string. That means fewer data conversions internally.

    source: How to get numeric types from MySQL using PDO?

    In this case there is PDO::ATTR_STRINGIFY_FETCHES which in your case should be set to true, also you can give try to PDO::ATTR_EMULATE_PREPARES attribute farther see: PDO MySQL: Use PDO::ATTR_EMULATE_PREPARES or not?

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

    Hope this helps in any case or anyone :))

    0 讨论(0)
提交回复
热议问题