将多个$ _Posts从表单添加到MYSQL DB中 - 使用循环?

时间:2014-11-26 15:47:31

标签: php mysql forms

专家交流>编程> Prog语言>脚本语言> PHP>使用A循环将多个帖子从表格添加到M Y S Q L D B中 您的问题已提交。 将多个$ _Posts从表单添加到MYSQL DB中 - 使用循环?! 提问者:runnerjp2005 您好,

以下代码添加额外的文本框行以添加更多数据。 但是我遇到循环问题并将它们添加到我的数据库中的问题。

我的方法是否正确,因为我得到了错误"为foreach()提供了无效的参数"

下面是我的代码

        <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
<?php
include "../include/db.php";
if (!empty($_POST['ok'])) {

    if (!empty($_POST['Loop'])) {
        $i = 0;
        echo "hi";
        foreach ($_POST['Loop'] as $r) {
            //add to database

            $dateFormated = split('/', $_POST['theDate' . $i]);
            $Date         = $dateFormated[2] . '-' . $dateFormated[1] . '-' . $dateFormated[0];
            // check if name only contains letters and whitespace

            $Sport = test_input($_POST["Sport" . $i]);
            // check if name only contains letters and whitespace
            $Pick  = test_input($_POST["Pick" . $i]);

            $Bookie = test_input($_POST["Bookie" . $i]);
            // check if name only contains letters and whitespace

            if (strpos($_POST["Odds" . $i], '/') !== false) {
                $Odds = round(fraction(test_input($_POST["Odds" . $i])), 2);
            } else {
                $Odds = test_input($_POST["Odds" . $i]);
            }
            // check if name only contains letters and whitespace
            $BackorLay = test_input($_POST["BackorLay" . $i]);
            // check if name only contains letters and whitespace

            $Stake = floatval(test_input($_POST["Stake" . $i]));
            // check if name only contains letters and whitespace



            $Com = test_input($_POST["Com" . $i]);
            // check if name only contains letters and whitespace


            $Outcome = test_input($_POST["Outcome" . $i]);
            // check if name only contains letters and whitespace



            $Reduction = test_input($_POST["Reduction" . $i]);
            // check if name only contains letters and whitespace



            $PlaceDiv = test_input($_POST["PlaceDiv" . $i]);
            // check if name only contains letters and whitespace
            if ($_POST['test' . $i] == 'EW') {
                $ew = "yes";
            } else {
                $ew = "no";
            }
            $i = $i + 1;

            $sql = "
INSERT INTO `Bets` 
( `Date`, `Sport`, `Pick`, `Bookie`, `Odds`, `BackorLay`, `Stake`, `ew`, `Com`, `Result`, `Reduction`, `PlaceDiv`)
VALUES
('$Date', '$Sport', '$Pick', '$Bookie', '$Odds', '$BackorLay', '$Stake', '$ew', '$Com', '$Outcome', '$Reduction', '$PlaceDiv')";

            $res = mysqli_query($db, $sql);
            if (!$res) {
                echo PHP_EOL . "FAIL: $sql";
                trigger_error(mysqli_error($db), E_USER_ERROR);
            }


        }
    }
}
?>
<div style="width:90%;margin:auto;">
    <h1>Add Bets</h1>
    <form method="post">
    <center>
<p>
    <input type="hidden" name="Loop" value="loop">

            <input id="theDate0" size="10" value="<?
echo date(" d/m/Y ");
?>" name="theDate0" type="text">


            <select id="Sport0" name="Sport0">
                <option>Horse Racing</option>
                <option>Football</option>
                <option>Greyhounds</option>
                <option>NFL</option>
            </select>


            <input id="Pick0" name="Pick0" type="text">



            <select id="Bookie0" name="Bookie0">
                <option>Bet365</option>
                <option>Betfred</option>
                <option>BetVictor</option>
                <option>Boylesports</option>
                <option>Bwin</option>
                <option>Centrebet</option>
                <option>Coral</option>
                <option>Ladbrokes</option>
                <option>Paddy Power</option>
                <option>Pinnacle Sports</option>
                <option>SBOBET</option>
                <option>Sky Bet</option>
                <option>Stan James</option>
                <option>unibet</option>
                <option>William Hill</option>
            </select>


            <input id="Odds0" name="Odds0" size="3" type="text">


            <select id="BackorLay0" name="BackorLay0">
                <option>Back</option>
                <option>Lay</option>
            </select>


            <input id="Stake0" name="Stake0" size="3" type="text">E/W<input name="EW0" ID="EW0" value="EW" type="checkbox" />


            <select id="Com0" name="Com0">
                <option>0</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>


            <select id="Outcome0" name="Outcome0">
                <option>Unknown</option>
                <option>Win</option>
                <option>Loss</option>
                <option>P</option>
                <option>E/W Win</option>
                <option>Void</option>
            </select>


            <select id="PlaceDiv0" name="PlaceDiv0">
                <option>5</option>
                <option>4</option>
            </select>

     <input onclick="addRow(this.form);" type="button" value="Add row" /> </p>

<div id="itemRows">
    </div>            <p><input type="submit" name="ok" value="Save Changes"></p>
        </center>    
    </form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
    rowNum ++;

    var row = '<p id="rowNum'+rowNum+'"><input id="theDate'+rowNum+'" size="10" value="<?
echo date(" d/m/Y ");
?>" name="theDate'+rowNum+'" type="text"><select id="Sport'+rowNum+'" name="Sport'+rowNum+'"><option>Horse Racing</option><option>Football</option><option>Greyhounds</option><option>NFL</option></select><input id="Pick'+rowNum+'" name="Pick'+rowNum+'" type="text"></td><td><select id="Bookie'+rowNum+'" name="Bookie'+rowNum+'"><option>Bet365</option><option>Betfred</option><option>BetVictor</option><option>Boylesports</option><option>Bwin</option><option>Centrebet</option><option>Coral</option><option>Ladbrokes</option><option>Paddy Power</option><option>Pinnacle Sports</option><option>SBOBET</option><option>Sky Bet</option><option>Stan James</option><option>unibet</option><option>William Hill</option></select><input id="Odds'+rowNum+'" name="Odds'+rowNum+'" size="3" type="text"><select id="BackorLay'+rowNum+'" name="BackorLay'+rowNum+'"><option>Back</option><option>Lay</option></select><input id="Stake'+rowNum+'" name="Stake'+rowNum+'" size="3" type="text">E/W<input name="EW'+rowNum+'" ID="EW'+rowNum+'" value="EW" type="checkbox" /><select id="Com'+rowNum+'" name="Com'+rowNum+'"><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select><select id="Outcome'+rowNum+'" name="Outcome'+rowNum+'"><option>Unknown</option><option>Win</option><option>Loss</option><option>P</option><option>E/W Win</option><option>Void</option></select><select id="PlaceDiv'+rowNum+'" name="PlaceDiv'+rowNum+'"><option>5</option><option>4</option></select><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';


    jQuery('#itemRows').append(row);
    frm.add_qty.value = '';
    frm.add_name.value = '';
}
function removeRow(rnum) {
    jQuery('#rowNum'+rnum).remove();
}
</script>
</body>    
</html>

---更新代码---

    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.js"></script>
<?php
include "../include/db.php";

function fraction($frac)
    {
    $fraction = explode("/", $frac);
    if ($fraction[1] != 0)
        {
        return $fraction[0] / $fraction[1];
        }

    return "Division by zero error!";
    }

function test_input($data)
    {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
    }

if (!empty($_POST['ok']))
    {
    if (!empty($_POST['Loop']))
        {
        $i = 0;
        echo "hi";
        foreach($_POST['theDate'] AS $i => $theDate)
            {

            // add to database

            $dateFormated = split('/', $_POST['theDate']);
            $Date = $dateFormated[2] . '-' . $dateFormated[1] . '-' . $dateFormated[0];

            // check if name only contains letters and whitespace

            $Sport = test_input($_POST["Sport"]);

            // check if name only contains letters and whitespace

            $Pick = test_input($_POST["Pick"]);
            $Bookie = test_input($_POST["Bookie"]);

            // check if name only contains letters and whitespace

            if (strpos($_POST["Odds"], '/') !== false)
                {
                $Odds = round(fraction(test_input($_POST["Odds"])) , 2);
                }
              else
                {
                $Odds = test_input($_POST["Odds"]);
                }

            // check if name only contains letters and whitespace

            $BackorLay = test_input($_POST["BackorLay"]);

            // check if name only contains letters and whitespace

            $Stake = floatval(test_input($_POST["Stake"]));

            // check if name only contains letters and whitespace

            $Com = test_input($_POST["Com"]);

            // check if name only contains letters and whitespace

            $Outcome = test_input($_POST["Outcome"]);

            // check if name only contains letters and whitespace

            $Reduction = test_input($_POST["Reduction"]);

            // check if name only contains letters and whitespace

            $PlaceDiv = test_input($_POST["PlaceDiv"]);

            // check if name only contains letters and whitespace

            if ($_POST['test'] == 'EW')
                {
                $ew = "yes";
                }
              else
                {
                $ew = "no";
                }

            $i = $i + 1;
            $sql = "
INSERT INTO `Bets` 
( `Date`, `Sport`, `Pick`, `Bookie`, `Odds`, `BackorLay`, `Stake`, `ew`, `Com`, `Result`, `Reduction`, `PlaceDiv`)
VALUES
('$Date', '$Sport', '$Pick', '$Bookie', '$Odds', '$BackorLay', '$Stake', '$ew', '$Com', '$Outcome', '$Reduction', '$PlaceDiv')";
            $res = mysqli_query($db, $sql);
            if (!$res)
                {
                echo PHP_EOL . "FAIL: $sql";
                trigger_error(mysqli_error($db) , E_USER_ERROR);
                }
            }
        }
    }

?>
<div style="width:90%;margin:auto;">
    <h1>Add Bets</h1>
    <form method="post">
    <center>
<p>
    <input type="hidden" name="Loop" value="loop">

            <input id="theDate[]" size="10" value="<?php
echo date(" d/m/Y "); ?>" name="theDate[]" type="text">


            <select id="Sport[]" name="Sport[]">
                <option>Horse Racing</option>
                <option>Football</option>
                <option>Greyhounds</option>
                <option>NFL</option>
            </select>


            <input id="Pick[]" name="Pick[]" type="text">



            <select id="Bookie[]" name="Bookie[]">
                <option>Bet365</option>
                <option>Betfred</option>
                <option>BetVictor</option>
                <option>Boylesports</option>
                <option>Bwin</option>
                <option>Centrebet</option>
                <option>Coral</option>
                <option>Ladbrokes</option>
                <option>Paddy Power</option>
                <option>Pinnacle Sports</option>
                <option>SBOBET</option>
                <option>Sky Bet</option>
                <option>Stan James</option>
                <option>unibet</option>
                <option>William Hill</option>
            </select>


            <input id="Odds[]" name="Odds[]" size="3" type="text">


            <select id="BackorLay[]" name="BackorLay[]">
                <option>Back</option>
                <option>Lay</option>
            </select>


            <input id="Stake[]" name="Stake[]" size="3" type="text">E/W<input name="EW[]" ID="EW[]" value="EW" type="checkbox" />


            <select id="Com[]" name="Com[]">
                <option>0</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>


            <select id="Outcome[]" name="Outcome[]">
                <option>Unknown</option>
                <option>Win</option>
                <option>Loss</option>
                <option>P</option>
                <option>E/W Win</option>
                <option>Void</option>
            </select>


            <select id="PlaceDiv[]" name="PlaceDiv[]">
                <option>5</option>
                <option>4</option>
            </select>

     <input onclick="addRow(this.form);" type="button" value="Add row" /> </p>

<div id="itemRows">
    </div>          <p><input type="submit" name="ok" value="Save Changes"></p>
        </center>   
    </form>
</div>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
    rowNum ++;

    var row = '<p id="rowNum'+rowNum+'"><input id="theDate[]" size="10" value="<?php
echo date(" d/m/Y "); ?>" name="theDate[]" type="text"><select id="Sport[]" name="Sport[]"><option>Horse Racing</option><option>Football</option><option>Greyhounds</option><option>NFL</option></select><input id="Pick[]" name="Pick[]" type="text"></td><td><select id="Bookie[]" name="Bookie[]"><option>Bet365</option><option>Betfred</option><option>BetVictor</option><option>Boylesports</option><option>Bwin</option><option>Centrebet</option><option>Coral</option><option>Ladbrokes</option><option>Paddy Power</option><option>Pinnacle Sports</option><option>SBOBET</option><option>Sky Bet</option><option>Stan James</option><option>unibet</option><option>William Hill</option></select><input id="Odds[]" name="Odds[]" size="3" type="text"><select id="BackorLay[]" name="BackorLay[]"><option>Back</option><option>Lay</option></select><input id="Stake[]" name="Stake[]" size="3" type="text">E/W<input name="EW[]" ID="EW[]" value="EW" type="checkbox" /><select id="Com[]" name="Com[]"><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select><select id="Outcome[]" name="Outcome[]"><option>Unknown</option><option>Win</option><option>Loss</option><option>P</option><option>E/W Win</option><option>Void</option></select><select id="PlaceDiv[]" name="PlaceDiv[]"><option>5</option><option>4</option></select><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';


    jQuery('#itemRows').append(row);
    frm.add_qty.value = '';
    frm.add_name.value = '';
}
function removeRow(rnum) {
    jQuery('#rowNum'+rnum).remove();
}
</script>

2 个答案:

答案 0 :(得分:0)

要循环播放数组,您必须按原样发送数据,因此您必须为输入字段命名并命名[]&#39;。这样,添加到这些字段的数据会添加到$ _POST中,作为&#39; name&#39;的元素。阵列。

示例:

<form action="" method="post">
    <input type="hidden" name="works[]" value="1">
    <input type="hidden" name="works[]" value="2">
    <input type="submit" name="submit" />
</form>

<?php 

    if (isset($_POST['submit'])) {
        if (!empty($_POST['works'])) {
            var_dump($_POST['works']);
        }
    }
?>

这会渲染一个包含&#39;的所有值的数组[]&#39;字段:

array(2) { [0]=> string(1) "1" [1]=> string(1) "2" }

答案 1 :(得分:0)

您可以对此做出很多方法改进,但我会尽量保持这个答案。

正如@devJunk在评论中所说,你的$ _POST [&#39;循环&#39;]包含字面上的&#39;循环&#39;。它不是一个数组,所以你不能用foreach循环它。

我发现您尝试做的事情是遍历您提交的所有行。有几种不同的方法可以实现这一目标。

最小更改选项

您目前正在为变量的末尾附加一个数字(即&#34; Bookie0&#34;,&#34; Bookie1&#34;等)。这将有效,但您需要为脚本的后端提供一种方法来了解您要提交的行数。因此,对隐藏的循环进行此更改:

<input type="hidden" name="Loop" id="Loop" value="1">

然后,在你的addRow()和removeRow()函数中,添加:

jQuery('#Loop').val((rowNum + 1));

确保在AFTER&#34; rowNum ++&#34;之后添加它。在你的addRow函数中。你还需要添加&#34; rowNum - &#34;到你的removeRow()函数,然后添加上面的内容。

这会将Loop设置为您拥有的行数的值。

然后,在处理帖子时,摆脱&#34; foreach($ _POST [&#39; Loop&#39;]为$ r)&#34;并用以下代替:

for ($i = 0; $i < $_POST['Loop']; $i++) {

(请注意,您将不再需要&#34; $ i = 0&#34;也不会&#34; $ i = $ i + 1&#34;在您的邮政处理中)

这将迭代您提交的许多行并进行处理。

改进的方法选项

如果要更改方法,可以使用HTML输入数组来完成此操作。基本上,不是使用&#34; Bookie0&#34;,&#34; Bookie1&#34;等,你可以让每个变量名都以&#34; []&#34;结束,就像&#34 ; Bookie []&#34;,&#34; Sport []&#34;等。方括号的添加意味着$ _POST [&#39; Bookie&#39;]将自动成为一个数组。

因此,在你的addRow和removeRow函数中,你不再需要担心增加或减少行号,因为那将不再相关。你根本不需要隐藏Loop。然后,在处理帖子时,你会做这样的事情:

foreach ($_POST['theDate'] AS $i => $theDate) {

其余的处理工作正常。