繁体   English   中英

MySQL在整数之前不存储零(字段设置为text(或varchar))

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

我正在通过HTML将表单提交到POST PHP页面,然后将该信息存储到MySQL数据库中。 其中一个输入字段是一个可以从零开始的数字字段。 我已经将HTML数据类型设置为表单上的文本,并尝试将MySQL数据类型设置为text和varchar,并且在整数被删除之前都将零数字设置为零。 我不太确定我做错了什么。

这是我创建表的PHP代码:

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

这是表单字段的样子:

<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>

使用这个,输入'cnum'的数字如0125保存为125.我做错了什么?

编辑:这是完整的代码,所以我很清楚我在做什么。 这不是一个很长的代码(可能是错误的,因为我试图把东西转移到这里)。

<?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>

经过大量调试后,我认为错误在这两个部分的某处。

第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)
);";

或者它可能在这一行:

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

代码似乎保持格式完美一直到这一行。 因此,我认为在插入MySQL数据库时会丢弃零。 我不知道为什么它会这样做......

intval()表示“获取字符串并将其转换为整数”,这就是导致字符串"01234"作为数字1234

$pairs[] = '('.intval($key).','.intval($value).')';删除它 对于数字字段,因为您要将其作为文本插入; 将其封装在引号'$value'

您正在将此字符串转换为此行的int:

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

之后,使用$pairs的值(现在包含两个整数)执行插入:

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

你应该替换:

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

有:

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

有人帮我意识到自己的错误。 我错过了$ pairs []行中的引号,而不是将其作为字符串输入MySQL,它以整数形式出现,这就是MySQL降低零的原因。 现在一切都很完美。

而不是intval你可以使用这样的东西

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

暂无
暂无

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

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