I have got the php, html code.
And I want to post the multiple checkbox values, but this does not work dunno why, I can print count or array, it prints(0), does not matter
the array values is always empty
<form action = 'main.php?w=creatNewTemplate2' method = 'post'>
<input type = 'text' name = 'templateName' maxlength = '30'/><br />
<input type= 'checkbox' name= 'exercises[]' value='A' />A<br />
<input type= 'checkbox' name= 'exercises[]' value='B' />B<br />
<input type = 'submit' value = 'Sukurti'/>
</form>
if($w == "creatNewTemplate2")
{
$d = $_POST['exercises'];
$ddd = count($d);
print_r($_POST);
}
I think this could work for you:
if($w == "creatNewTemplate2")
{
$d = $_POST['exercises'];
$ddd = count($d);
for ($x = 0; $x < $ddd; $x++) {
echo $_POST['exercises'][$x].'<br>';
}
}
If you use same name you need to loop them
This should be work
Or you can change the two checkbox to select multiple
<form action="main.php?w=creatNewTemplate2" method="post">
<input type="text" name="templateName" maxlength="30"/><br/>
<select multiple name="exercices[]">
<option>A</option>
<option>B</option>
</select>
<input type="submit" value="Sukurti"/>
</form>
<?php
if($_GET["w"] == "creatNewTemplate2")
{
foreach ($_POST["exercises"] as $ex) {
echo $ex . '<br>';
}
}
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>
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.
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" }
<form method="POST" name="mailform" action="sendmail.php">
<fieldset>
<?php
require_once("mysql_connect.php");
$sql = mysql_query( " SELECT NAME FROM TABLE WHERE ID = ( SELECT ID FROM TABLE2 WHERE COLUMN = '$USERNAME') ORDER BY NAME");
echo "<select>";
while($row = mysql_fetch_array($sql)){
echo "<option value='".$row["NAME"]."'>".$row["NAME"]."</option>";
}mysql_free_result($sql);
echo "</select>";
?>
<input type="text" name = "name" placeholder = "name Required" ><br \><br \>
<input type="checkbox" name="instance[]" value="yes" checked="checked" \>instance1><br>
<input type="checkbox" name="instance[]" value="Yes" \>instance2<br><br \>
<input type="submit" name="email" value="Send Mail">
</fieldset> <br \>
</form> <br \><br \>
This the part of the code. I need to build sendemail.php which should have the value from dynamic select list, and value from the check boxes.
<?php
require_once("mysql_connect.php");
$sql = mysql_query( " SELECT NAME FROM TABLE WHERE ID = ( SELECT ID FROM TABLE2 WHERE COLUMN = '$USERNAME') ORDER BY NAME");
echo "<select name='selection'>";
while($row = mysql_fetch_array($sql)){
echo "<option value='".$row["NAME"]."'>".$row["NAME"]."</option>";
}mysql_free_result($sql);
echo "</select>";
?>
change your php code with above.. you'll get $_POST['selection'] from dynamic select list.
Edit:
You'll get $_POST['instance'] array.
<?php
$selected = $_POST['selection'];
$instances = array();
foreach ($_POST['instance'] as $instance)
{
$instances[] = $instance;
}
?>
Now, you'll have $selected as dynamic selected value and $instances have array of checked checkboxes.
To get the value of a selected item in a list
<select id="items" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
</select>
$selected_val = $_POST['items'];
To get the selected checkbox values
Red <input type="checkbox" name="color[]" id="color" value="red">
Green <input type="checkbox" name="color[]" id="color" value="green">
$colorsChecked = $_GET['color'];
foreach ($color as $colorsChecked)
{
echo $color;
}
your select box must has a name.
echo "<select name='cbouser'>";
after post you need to use $_POST["cbouser"] or $_REQUEST["cbouser"]
I have a loop which generates a couple of fields which could be field in. I want to POST all the values from these fields into another php page.
The first page:
for ($i = 1; $i <= 10; $i++) {
print "
<form action='2.php' method='post' id='test_form'>
<input name='value-$i' type='text' />
<input id='send' name='send' type='submit' value='Sent' />
</form>
";
}
The second page:
while ( ) {
$valuer= $_POST['value'];
}
<input name='value[$i]' type='text' />
^--^---- note the []
Then
$fifth_value = $_POST['value'][5];
I am fairly new to php. I am trying to update the score everytime I loop over this array. my code only works if the first value of the listbox was selected by the user and it gives a zero if its not selected. please help.
This is A.php
{
$SkillsArray = array();
$Score=0;
$SkillsArray = $_POST['DutiesDesc'];
//foreach($SkillsArray as $key =>$value )
{
$Sentence = $SkillsArray[0]." ".$SkillsArray[1]." ".$SkillsArray[2]." ".$SkillsArray[3]." ".$SkillsArray[4]." ".$SkillsArray[5]." ".$SkillsArray[6]." ".$SkillsArray[7 ]." ".$SkillsArray[8]." ".$SkillsArray[9]." ".$SkillsArray[10];
}
//Get the applicants score
for($i=0;$i<11;$i++)
{
if ($SkillsArray[$i] == $Text[$i])
{
$Score = $Score+$Val[$i];
}
}
} //**** The following is the HTML part of the code(form)
<form action = "A.php" method ="POST" enctype="multipart/form-data">
<label for="Position">Position:</label><input type="type" name="Position" size="35" /><br />
</p>
<p>
<!-- <label for="DutiesDesc">Duties Description: </label><textarea name="DutiesDesc" cols="30" rows="5" /></textarea>--> <br />
Job Description
<select name="DutiesDesc[]" size=5 multiple="multiple">
<option value="<?php echo $Arow['TextF1']?>"><?php echo $Arow['TextF1']?></option>
<option value="<?php echo $Arow['TextF2']?>"><?php echo $Arow['TextF2']?></option>
<option value="<?php echo $Arow['TextF3']?>"><?php echo $Arow['TextF3']?></option>
<option value="<?php echo $Arow['TextF4']?>"><?php echo $Arow['TextF4']?></option>
<option value="<?php echo $Arow['TextF5']?>"><?php echo $Arow['TextF5']?></option>
<option value="<?php echo $Arow['TextF6']?>"><?php echo $Arow['TextF6']?></option>
<option value="<?php echo $Arow['TextF7']?>"><?php echo $Arow['TextF7']?></option>
<option value="<?php echo $Arow['TextF8']?>"><?php echo $Arow['TextF8']?></option>
<option value="<?php echo $Arow['TextF9']?>"><?php echo $Arow['TextF9']?></option>
<option value="<?php echo $Arow['TextF10']?>"><?php echo $Arow['TextF10']?></option>
<option value="<?php echo $Arow['TextF11']?>"><?php echo $Arow['TextF11']?></option>
</select><br />
The values in the array $SkillsArray do not have the same index as your $Text array. If you select the 3rd (lets say the value is "c") and 5th (e.g. "e") item in your list, the array $SkillsArray will contain the following:
$SkillsArray[0] = "c";
$SkillsArray[1] = "e";
So what you need is a simple search over your $SkillsArray, since you can't rely on the indexes being conform with your $Text array.
if (is_array($SkillsArray)) {
for($i = 0; $i < count($Text); $i++) {
if (array_search($Text[$i], $SkillsArray) !== false) {
$Score += $Val[$i];
}
}
}
Please do remember to check, if $SkillsArray is indeed an array. If the user doesn't check any skills, the function array_search will return false for every item, which will result in the maximum score.
Documentation for functions: count, array_search, is_array
The
for($i=0;$i<11;$i++)
{
for($j=0;$j<11;$j++)
{
if (($SkillsArray[$i] == $Text[$j]))
{
$Score = $Score+$Val[$j];
}
}
This required a second loop in order to work properley:)