在 MySQL 中保持领先零

Keeping lead Zero in MySQL

我有一个带有 varchar 列的 table。我使用值为 01、02、03、04 .... 10、11、12 等的 select 形式将数据存储在此列中。我的问题是,当我提交表单时,前导 'Zero' 被删除了。如何保持前导零?

**

NB. I have checked other similar posts but they don't have the solution for my issue. I have tried var/char/text and still it's not working hence why I posted this question if there's another way to get this done.

**

<form method=post enctype="multipart/form-data">
<select name="dd">
    <option selected="selected">Day</option>
    <option value='01'>01</option>
    <option value='02'>02</option>
    <option value='03'>03</option>
    <option value='04'>04</option>
    <option value='05'>05</option>
    <option value='06'>06</option>
    <option value='07'>07</option>
    <option value='08'>08</option>
    <option value='09'>09</option>
    <option value='10'>10</option>
    <option value='11'>11</option>
  </select>

<select name="mm">
    <option selected="selected">Month</option>
    <option value='01'>01</option>
    <option value='02'>02</option>
    <option value='03'>03</option>
    <option value='04'>04</option>
    <option value='05'>05</option>
    <option value='06'>06</option>
    <option value='07'>07</option>
    <option value='08'>08</option>
    <option value='09'>09</option>
    <option value='10'>10</option>
    <option value='11'>11</option>
  </select>
</form>

MySQL如下;

    $caption = $_POST['dd'].-$_POST['mm'];
    
    $sql = "INSERT INTO pages SET caption = '$caption'";

使用 sprintf 格式化您的值:

$caption = sprintf("%02d-%02d", $_POST['dd'], $_POST['mm']);

此处的关键是将数据 作为字符串处理 ,不要像 -$_POST['mm'] 那样对其进行数学运算,后者会将其视为数字。在数字中,前导零总是被省略,因为它们总是存在的。就 CPU 而言,10 实际上类似于 0x0000000a