0

Experts Exchange > Programming > Prog Languages > Scripting Languages > PHP > Adding Multiple Posts From Form Into M Y S Q L D B Using A Loop Your question has been submitted. Adding multiple $_Posts from form into MYSQL DB - Using a loop?! Asked by: runnerjp2005 Hi,

The following code adds extra rows of text boxes to add further data. But im having issue with looping through them and adding them into my database.

Is my mothod correct as im getting the error "Invalid argument supplied for foreach() "

below is my code

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

---Update code---

    <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>
5
  • It's throwing that error because 'Loop' is just a single value and not an array. I'm not sure what you were trying to achieve with it. What is the loop input supposed to contain? Commented Nov 26, 2014 at 15:53
  • I was trying to make it so it loops through all the hidden fields that contain loop.... i thought even if there is one loop it would work? - have you any suggestions on how i would collect the data? Commented Nov 26, 2014 at 15:59
  • you would have to name the inputs 'loop[]', so data gets sent as an array. Commented Nov 26, 2014 at 16:00
  • sorry which part am i naming loop[]??? Commented Nov 26, 2014 at 16:08
  • I'm showing you an example on an answer. Commented Nov 26, 2014 at 16:08

2 Answers 2

0

There are a lot of methodology improvements you could make to this, but I'll try to keep this answer as direct as possible.

As @devJunk said in the comment, your $_POST['Loop'] contains, literally, 'loop'. It is not an array, so you can't loop it with a foreach.

I see that what you're trying to do is iterate through all the rows you've submitted. There are a couple different ways to achieve this.

Minimal Changes Option

You are currently appending a number to the end of your variables (i.e. "Bookie0", "Bookie1", etc.). This will work, but you need to give the backend of the script a way to know how many rows you are submitting. So make this change to your Loop hidden:

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

Then, in your addRow() and removeRow() functions, add this:

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

Make sure you add it AFTER "rowNum ++" in your addRow function. You also need to add "rowNum --" to your removeRow() function, and add the above after that.

This will set Loop to be the value of the number of rows you have.

Then, when processing the post, get rid of "foreach ($_POST['Loop'] as $r)" and replace it with this:

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

(Note that you will no longer need "$i = 0" nor "$i = $i + 1" in your post handling)

This will iterate however many rows you have submitted and do your processing.

Improved Methodology Option

If you want to change your methodology, you can use HTML Input Arrays to accomplish this instead. Basically, instead of using "Bookie0", "Bookie1", etc., you can just make every variable name end with "[]", like "Bookie[]", "Sport[]", etc. The addition of the square braces means that $_POST['Bookie'] will automatically be an array.

So in your addRow and removeRow functions, you would no longer have to worry about incrementing or decrementing the row number because that would no longer be relevant. you wouldn't need the Loop hidden at all. Then, when processing the post, you would do something like this:

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

And the rest of your processing should work fine.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi Eric,i followed the above (not removed the addrow bits nor the hidden loop but whe ni run the code sall data fields are blank :S i have updated the code above
Remember that your POST variables are now arrays. So you just need to give all the subsequent post variables the index number by appending [$i] to the end of the $_POST['whatever']. Ex: $Pick = test_input($_POST["Pick"][$i]); $Bookie = test_input($_POST["Bookie"][$i]);
I realize now when I said "the rest of your processing should work fine", that was not actually accurate =) My apologies.
Also -- you can't really use 'id="Name[]"' in your inputs. I don't think this will cause any problems to the processing of the data, but if you try to get an object by ID using jQuery I think you will have problems. You can either eliminate the ID attribute completely (and use name-based selectors in jQuery, if needed later), or you can use the rowNum in your javascript to define only the ID attribute.
0

In order to loop through an array, you have to send data as such, so you have to name your input fields 'name[]'. That way, data added to those fields is added to $_POST as elements of the 'name' array.

Example:

<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']);
        }
    }
?>

This renders an array with all the values of 'works[]' fields:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.