3

HTMLを介してフォームをPOSTPHPページに送信し、POSTPHPページはその情報をMySQLデータベースに保存します。入力フィールドの1つは、ゼロから開始できる数値フィールドです。フォームでHTMLデータ型をtextに設定し、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>

多くのデバッグを行った後、エラーはこれら2つのセクションのどこかにあると思います。

セクション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データベースに挿入されている間にゼロが削除されていると思います。なぜそれをしているのかわかりませんが...

4

4 に答える 4

3

intval()は「文字列を取得して整数に変換する」ことを意味し、これが文字列"01234"を数値として出力する原因1234です。

$pairs[] = '('.intval($key).','.intval($value).')';テキストとして挿入したいので、数値フィールドから削除します。引用符で囲みます'$value'

于 2012-08-07T02:38:34.740 に答える
1

次の行で文字列を int に変換しています。

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

その後、次の値を使用して挿入を行います$pairs(現在は 2 つの整数が含まれています)。

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

以下を置き換える必要があります。

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

と:

$pairs[] = '('.$key.','.$value.')'; 
于 2012-08-07T02:40:05.847 に答える
1

誰かが私の過ちに気付くのを助けてくれました。$pairs[] 行に引用符がありませんでした。それを文字列として MySQL に入力する代わりに、整数として入力していたため、MySQL はゼロを削除していました。現在、すべてが完全に機能しています。

于 2012-08-07T20:10:09.203 に答える
0

代わりに、intvalこのようなものを使用できます

function toNumeric($str)
{
    return is_numeric($str) ? $str : preg_replace('/\D/',null,$str);
}
于 2012-08-07T02:42:41.783 に答える