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

后端 未结 2 1491
余生分开走
余生分开走 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: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 :))

提交回复
热议问题