I start with the following:
<form action="" method="post" enctype="multipart/form-data" id="form">
<?php foreach($attributes as $attribute){ ?>
<input type="checkbox" name="attribute[][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
<?php } ?>
</form>
So each $attribute has a checkbox and a text input; whenever someone would check (one or more boxes) and would insert text (only to the checked items) I want to get in the DB the [attr_id] and the [attr_name] for the specific item.
So I continue with the following:
if(isset($_POST['attribute'])){
foreach($_POST['attribute'] as $attribute){
$attr_id = $attribute['attr_id'];
$attr_name = $attribute['attr_name'];
"INSERT INTO " . DB_PREFIX . "attribute_xref SET productid = '" . $productid . "', attribute_id='". $attr_id ."', attribute_name='" . $attr_name . "'";
}
}
But, the result is a little different as of I would have expected. Every time a box is checked and its text input is typed, their values are sent to two different DB rows:
productid -- attribute_id -- attribute_name
10 -- 102 -- empty
10 -- 0 -- somename
On the above second row the attribute_id has zero value for not being checked.
I cannot get the whole picture where is my mistake.
Finally. The tricky answer was to add an identical numerical index to the associative inputs like this:
<form action="" method="post" enctype="multipart/form-data" id="form">
<?php foreach($attributes as $attribute){ ?>
<input type="checkbox" name="attribute[i][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[i][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
<?php } ?>
</form>
where "i" in my case would take the variable number from 'attribute_id':
<input type="checkbox" name="attribute[<?php echo $attribute['attribute_id']; ?>][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[<?php echo $attribute['attribute_id']; ?>][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
Hopefully my answer would help somebody in the future, too.
Related
In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)
I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}
Am looping products out from product table to add them to cart table. only the selected product by checking the checkbox should be added, but if you select, the selected ones do not correspond..
HERE IS THE HTML GETTING THE PRODUCTS OUT
<html>
<form action="#" id="" class="horizontal-form" method="post">
<?php
$LISTP = "SELECT * FROM products ORDER BY id";
$sn = 0;
$stmt = $pdo->prepare($LISTP);
$stmt->execute();
while($list = $stmt->fetch(PDO::FETCH_ASSOC)){
$sn = $sn + 1;
$ID = $list['id'];
$NAME = $list['name'];
?>
<input type="checkbox" name="slected[]" class="checkboxes" value="1" />
<input type="hidden" name="productid[]" class="" value="<?php echo $ID;?>" />
<input type="text" name="name[]" class="" value="<?php echo $NAME;?>" />
<?php }?> </form>
<?php
// now when we submot the form
$slected = $_POST['slected'];
$prod = $_POST['productid'];
$name = $_POST['name'];
foreach($prod as $key => $product){
if($slected[$key]>0){
echo $product.' '.$name[$key].' '.#$slected[#$key].'--<br>';
}
// the problem is here, if you check all product it will work well, but if you check the second one
// it would echo the second one giving it the name of the first one which was not checked at all
?>
I used to do this the same way in the past, and have discovered what I think is a better way. Rather than having a hidden input that stores the ID, just use the ID as the index for all of the form variable keys:
<input type="checkbox" name="slected[<?php echo $ID; ?>]" class="checkboxes" value="1" />
<input type="text" name="name[<?php echo $ID; ?>]" class="" value="<?php echo $NAME;?>" />
Then, your PHP can be simplified:
// now when we submot the form
$slected = $_POST['slected'];
$name = $_POST['name'];
foreach( (array)$slected as $ID => $on ) {
echo $product . ' ' . $name[$ID] . ' ' . $ID . '--<br>';
}
So - basically, your $slected variable will contain an array of only items that are selected, AND you have the product ID built in to the $slected array.
I am a little stuck with this. I am trying to insert groups of items only if that groups checkbox is clicked. I have tested the SQL insert without the checkboxes, and the SQL works perfectly and inserts the data. But when I added the checkboxes and if/else statement, it started to give me troubles.
For example:
-If I select group 1 and not group 2 - the SQL works correctly only inserting group 1 data
-If I select group 2 and not group 1 - The insert still inserts group 1 data
-If I select group 1 and group 2 - The SQL inserts two rows of group 1 data
-If I do not select any groups, then I get "Warning: Invalid argument supplied for foreach() in /home..." - which I will sort out later.
I have marked "Group 1" and "Group 2". I need the code to insert only the groups if checkbox is clicked, and ignore the non clicked checkbox groups. Any help would be great. Thanks.
I have been testing with the following code:
Form:
<form id="Form" method="post" action="/random.php" name="Form">
<input id="itemCurrency" type="hidden" value="2" name="itemCurrency"></input>
<div class="row">
<div class="col-lg-4">
<div class="itemHolder">
<img class="itemImg thumbnail" src="http://images.com/i/images.jpg"></img>
<div class="itemName">swim Shorts Wi...</div><
<div class="itemPrice">$33.33</div>
<div class="itemHref"><a target="_blank" href="http://random.com/product.aspx?id=40"> Visit Item Page </a></div>
</div>
</div>
//GROUP 1
<input id="itemCheckBox[]" type="checkbox" value="checked" name="itemCheckBox[]"></input>
<input id="itemName[]" type="hidden" value="some random text" name="itemName[]"></input>
<input id="itemHref[]" type="hidden" value="http://random.com/product.aspx?id=2140" name="itemHref[]"></input>
<input id="itemImg[]" type="hidden" value="http://images.com/i/image1s.jpg" name="itemImg[]"></input>
<input id="itemPrice[]" type="hidden" value="$37.33" name="itemPrice[]"></input>
//END GROUP 1
<div class="col-lg-4">
<div class="itemHolder">
<img class="itemImg thumbnail" src="http://images.com/i/image_xl.jpg"></img>
<div class="itemName">Bomber Jacket With Fur</div>
<div class="itemPrice"> $88.88</div>
<div class="itemHref"><a target="_blank" href="http://random.com/Bomber-Jacket-With-fur/..">Visit Item Page</a></div>
</div>
</div>
//GROUP 2
<input id="itemCheckBox[]" type="checkbox" value="checked" name="itemCheckBox[]"></input>
<input id="itemName[]" type="hidden" value="Bomber Jacket With Fur" name="itemName[]"></input>
<input id="itemHref[]" type="hidden" value="http://random.com/Bomber-Jacket-With-fur/.." name="itemHref[]"></input>
<input id="itemImg[]" type="hidden" value="http://images.com/i/image_xl.jpg" name="itemImg[]"></input>
<input id="itemPrice[]" type="hidden" value="$88.88" name="itemPrice[]"></input>
//END GROUP 2
<input id="site" type="hidden" value="1" name="site"></input>
<input id="submit_form" type="submit" value="yes" name="submit_form"></input>
</form>
PHP
if($submitForm == "yes" && $site == "1") {
foreach($_POST['itemCheckBox'] as $key => $val)
{
$fields[] = array(
'itemCheckBox'=>$_POST['itemCheckBox'] [$key],
'itemName' =>$_POST['itemName'] [$key],
'itemHref' =>$_POST['itemHref'] [$key],
'itemImg' =>$_POST['itemImg'] [$key],
'itemPrice' =>$_POST['itemPrice'][$key] );
//Remove non numaric characters from price(leave commas).
$itemPrice = preg_replace('/[^0-9,.]/s', '', $itemPrice);
//Data fields not in form
$userId = "username";
$userIp = $_SERVER['REMOTE_ADDR'];
$itemType = "ADD LATER";
$itemOutFit = "ADD LATER";
$site = "1";
$itemSale = "1";
//Only insert if checkbox is clicked --NOT WORKING, ????
if (isset($_POST['itemCheckBox'])){
echo "CHECKED";
echo "<br>";
/*** INSERT data ***/
$sql = "INSERT INTO items (userId,itemHref,itemImg,itemPrice,itemName,userIp,itemSite,itemType,itemCurrency,itemOutFit,itemSale) VALUES (:userId,:itemHref,:itemImg,:itemPrice,:itemName,:userIp,:itemSite,:itemType,:itemCurrency,:itemOutFit,:itemSale)";
$q = $conn->prepare($sql);
$q->execute(array(':userId'=>$userId,
':itemHref'=>$itemHref[$key],
':itemImg'=>$itemImg[$key],
':itemPrice'=>$itemPrice[$key],
':itemName'=>$itemName[$key],
':userIp'=>$userIp,
':itemSite'=>$itemSite,
':itemType'=>$itemType,
':itemCurrency'=>$itemCurrency,
':itemOutFit'=>$itemOutFit,
':itemSale'=>$itemSale));
} else {
echo "NOT CHECKED";
echo "<br>";
}
/*
echo $conn->errorCode();
echo "<br>"; ('SET CHARACTER SET utf8')
echo $conn->errorInfo();
echo "<br>";
//die(print_r($q->errorInfo(), true));
*/
}
UPDATE Tried to strip php down to basic code, still no luck. Does the same thing....anyone have an idea how I can fix this.
foreach($_POST['itemCheckBox'] as $key => $val)
{
$i = 0;
$itemCheckBox = $_POST['itemCheckBox'];
$itemName = $_POST['itemName'];
$itemHref = $_POST['itemHref'];
$itemImg = $_POST['itemImg'];
$itemPrice = $_POST['itemPrice'];
echo $i;
echo "<br>";
$i = $i +1;
if (isset($_POST['itemCheckBox'])){
echo "<br>";
echo "CHECKED";
echo "<br>";
echo "<br>";
echo $itemCheckBox[$i];
echo "<br>";
echo $itemName[$i];
echo "<br>";
echo $itemHref[$i];
echo "<br>";
echo $itemImg[$i];
echo "<br>";
echo $itemPrice[$i];
} else {
echo "NOT CHECKED";
echo "<br>";
$i = $i +1;
}
}
A couple things I spots that may be contributing to the issue:
In your PHP you have a line that has this:
//Remove non numaric characters from price(leave commas).
$itemPrice = preg_replace('/[^0-9,.]/s', '', $itemPrice);
I don't see where $itemPrice is defined though, should it be:
$itemPrice = preg_replace('/[^0-9,.]/s', '', $fields['itemPrice']);
Your issue of getting the "Warning: Invalid argument supplied for foreach() in /home..." can be solved by checking to make sure it exists and is an array beforelooping. You can use !empty() and is_array() to check.
if(!empty($_POST['itemCheckBox']) and is_array($_POST['itemCheckBox'])){}
Side Issue:
Your IDs for the inputs are all the same, "itemCheckBox[]", "itemName[]", etc.. are the same ID used for all of them. This may cause problems in the future if you want to use javascript or css properly.
Edit:
In your revised example the issue is that each time it cycles into the loop it is setting $i=0 because you declare it at the top of the foreach. If you go back to using the $key as the index it should work. See below:
//GROUP 1 checkbox
<input id="itemCheckBox[]" type="checkbox" value="0" name="itemCheckBox[]"></input>
//GROUP 2 checkbox
<input id="itemCheckBox[]" type="checkbox" value="1" name="itemCheckBox[]"></input>
I may also advise that you adjust your HTML items to match the Key you are passing:
<input id="itemName[1]" type="hidden" value="Bomber Jacket With Fur" name="itemName[]"></input>
<input id="itemHref[1]" type="hidden" value="http://random.com/Bomber-Jacket-With-fur/.." name="itemHref[]"></input>
<input id="itemImg[1]" type="hidden" value="http://images.com/i/image_xl.jpg" name="itemImg[]"></input>
<input id="itemPrice[1]" type="hidden" value="$88.88" name="itemPrice[]"></input>
foreach($_POST['itemCheckBox'] as $key => $val) {
$itemCheckBox = $_POST['itemCheckBox'];
$itemName = $_POST['itemName'];
$itemHref = $_POST['itemHref'];
$itemImg = $_POST['itemImg'];
$itemPrice = $_POST['itemPrice'];
if (isset($_POST['itemCheckBox'])){
echo "<br>";
echo "CHECKED";
echo $itemCheckBox[$key];
echo "<br>";
echo "<br>";
echo $itemCheckBox[$itemCheckBox[$key]];
echo "<br>";
echo $itemName[$itemCheckBox[$key]];
echo "<br>";
echo $itemHref[$itemCheckBox[$key]];
echo "<br>";
echo $itemImg[$itemCheckBox[$key]];
echo "<br>";
echo $itemPrice[$itemCheckBox[$key]];
} else {
echo "NOT CHECKED";
echo "<br>";
}
}
I am having the hardest time figuring out something that I think should be simple. I need to update multiple rows in my database with one submit button. I have it working with a submit for each row now, but I need to combine it. Here's what I'm trying. Where have I gone wrong? (I've been going off of multiple tutorials I found online and I think I have things all mixed up).
Here's the form:
<?php foreach ($teams as $team):
$id[]=$team['id'];?>
<form action="?update" method="post">
<div class="team-box">
<h2><?php echo $team['name'] ?></h2>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $team['name'] ?>" />
<label for="name">Match Wins:</label>
<input type="text" name="mwins" value="<?php echo $team['mwins'] ?>" />
<label for="name">Match Losses:</label>
<input type="text" name="mlosses" value="<?php echo $team['mlosses'] ?>" />
<label for="name">Match Ties:</label>
<input type="text" name="mties" value="<?php echo $team['mties'] ?>" />
<label for="name">Game Wins:</label>
<input type="text" name="gwins" value="<?php echo $team['gwins'] ?>" />
<label for="name">Game Losses:</label>
<input type="text" name="glosses" value="<?php echo $team['glosses'] ?>" />
<input type="hidden" name="id" value="<?php echo $team['id'] ?>" />
</div>
Here's the PHP to handle the UPDATE:
try
{
foreach($_POST['id'] as $id) {
$sql = 'UPDATE teams SET
name = "' . $_POST['name'.$id] . '",
mwins = "' . $_POST['mwins'.$id] . '",
mlosses = "' . $_POST['mlosses'.$id] . '",
mties = "' . $_POST['mties'.$id] . '",
gwins = "' . $_POST['gwins'.$id] . '",
glosses = "' . $_POST['glosses'.$id] . '"
WHERE id = "' . $_POST['id'.$id] . '"';
$pdo->exec($sql);
}
}
catch (PDOException $e)
{
$error = 'Error adding submitted team: ' . $e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
Thanks in advance!
There are a couple of things that need fixing.
The FORM must be outside the foreach.
The '...name="name" value="...', to agree with the _POST code, should read instead:
... name="name" value="...
This way, a single POST will submit, say,
name123="Rangers"
mwins174="123"
Then you need all IDs. You can do that by issuing, in the foreach, this:
<input type="hidden" name="id[]" value="<?php print $team['id']; ?>" />
This will result in HTML:
<input type="hidden" name="id[]" value="123" />
...
<input type="hidden" name="id[]" value="456" />
and in $_POST['id'] being an array containing 123, 456 and so on.
You could also put in HTML:
<input type="text" name="name[<?php print $team['id']; ?>]" value="...
so that $_POST['name'] would be a vector with the same keys as the values of id, and therefore:
foreach($id as $team_id)
{
// Pseudocode
UPDATE... SET name=$name[$team_id]... WHERE id = $team_id;
}
This way you have one SUBMIT, and multiple UPDATEs.
Since all your field names change for each UPDATE query, you will need to execute separate queries as you already do. I don't think you would be able to perform a single UPDATE query.
I don't understand, what's wrong with executing several update queries?