简体   繁体   中英

MySQL Not Storing Zero Before Integers (fields are set to text (or varchar))

I'm submitting a form via HTML into a POST PHP page, which is then storing that info into the MySQL database. One of the input fields is a number field that can start with zero. I've set the HTML data type to text on the form and tried setting the MySQL data type to text and varchar, and both times the zero before the integer gets dropped. I'm not quite sure what I'm doing wrong.

Here is my PHP code for table creation:

$sql = "CREATE TABLE IF NOT EXISTS $tablename_db (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
num text(4),
amnt DECIMAL(8,2)
);";

And here is what the form field looks like:

<div id="input1" class="cinput">
    # (last 4 digits): <input id="cnum" type="text" name="num[]" maxlength="4"     size="4" /> Amount: <input id="camnt" type="int" name="amnt[]" /> </br>
</div>

Using this, a number like 0125 inputted to 'cnum' is saved as 125. What am I doing wrong?

EDIT: Here is the code in its entirety, just so it's clear what I'm doing. It's not a very long code (possible typos as I tried to transfer things onto here).

<?php

if(isset($_POST['submit']))
{
//Get Current User Login
global $current_user;
$current_user = wp_get_current_user();
$ulog = $current_user->user_login;
$tablename = "db_".$ulog;

//Check To See If User Has Already Created Table
$sql = "CREATE TABLE IF NOT EXISTS $tablename (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
num text(4),
amnt DECIMAL(8,2)
);";

mysql_query($sql);

$num = $_POST['num'];
$amnt = $_POST['amnt'];

$items = array_combine($num,$amnt);
$pairs = array();

foreach($items as $key=>$value)
{
    if($key != 'submit')
    {   
        if($value != '')
        {
            $pairs[] = '('.intval($key).','.intval($value).')';
        }
    }
}

if (!mysql_query('INSERT INTO ' .$tablename. '(num, amnt) VALUES '.implode(',',$pairs)))
    die('Error: ' . mysql_error());
    else
        echo '<strong>', "Your information has been submitted and will be added to your account upon approval.", '</strong>', "/n";


}
?>

<html>

<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        $('#btnAdd').click(function() {
            var num     = $('.ccinput').length; // how many "duplicatable" input fields we currently have
            var newNum  = new Number(num + 1);      // the numeric ID of the new input field being added

            // create the new element via clone(), and manipulate it's ID using newNum value
            var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);

            // insert the new element after the last "duplicatable" input field
            $('#input' + num).after(newElem);

            // enable the "remove" button
            $('#btnDel').attr('disabled','');

            // business rule: you can only add 20 names
            if (newNum == 20)
                $('#btnAdd').attr('disabled','disabled');
        });

        $('#btnDel').click(function() {
            var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
            $('#input' + num).remove();     // remove the last element

            // enable the "add" button
            $('#btnAdd').attr('disabled','');

            // if only one element remains, disable the "remove" button
            if (num-1 == 1)
                $('#btnDel').attr('disabled','disabled');
        });

        $('#btnDel').attr('disabled','disabled');
    });
</script>
</head>

<body>

Please fill in your information in the form below and press submit. If you need to add    more, please click the "Add" button at the bottom of the form. You may enter a maximum of   20 at a time. Leave all unused fields blank.

<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<fieldset>
<legend>Information:</legend>
<div id="input1" class="ccinput">
    # (last 4 digits): <input id="cnum" type="text" name="num[]" maxlength="4" size="4" /> Amount: <input id="camnt" type="int" name="amnt[]" /> </br>
</div>
<div>
    <input type="button" id="btnAdd" value="Add" />
    <input type="button" id="btnDel" value="Remove" />
</div>
</fieldset>
<input type="submit" value="Submit" name="submit" />
</form>

</body>
</html>

After much debugging, I believe that the error is somewhere in these two sections.

Section 1:

$sql = "CREATE TABLE IF NOT EXISTS $tablename_db (
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
num text(4),
amnt DECIMAL(8,2)
);";

Or it might be in this line:

if (!mysql_query('INSERT INTO ' .$tablename. '(num, amnt) VALUES '.implode(',',$pairs)))

The code seems to maintain the format perfectly all the way up to this line. Therefore I think that the zero is being dropped while being inserted into the MySQL database. I'm not sure why it's doing it though...

intval() means "take the string and convert it to an integer", and this is what is causing the string "01234" to come out as the number 1234 .

Remove it from $pairs[] = '('.intval($key).','.intval($value).')'; and for the number field, since you want to insert it as text; encapsulate it in quotes '$value' .

You are converting your string to int at this line:

$pairs[] = '('.intval($key).','.intval($value).')';

After that, you do the insert, using the values from $pairs (which now contains two integers):

mysql_query('INSERT INTO ' .$tablename. '(num, amnt) VALUES '.implode(',',$pairs))

You should replace:

$pairs[] = '('.intval($key).','.intval($value).')';

with:

$pairs[] = '('.$key.','.$value.')'; 

Someone helped me realize my mistake. I was missing a quotation in the $pairs[] line and instead of entering it into MySQL as a string, it was going in as an integer and that's why MySQL was dropping the zero. Everything is working perfectly now.

instead of intval you can use something like this

function toNumeric($str)
{
    return is_numeric($str) ? $str : preg_replace('/\D/',null,$str);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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