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