Check form before submit - php

The form/table filled with data based on the the status. So the rows in the table are build dynamically.
What i want is that the person who wants to submit the form, has filled in the three fields (STIN / STOUT / REASON) (are dropdown menu's) and the field ITEM must be filled in from the database (not a user input).
If it was one row i think it would be easy, but it depends on the status of an order how many rows it will display and depends on the field ITEM if it has an ITEM.
Example:
Row 1 has the item STIN is selected STOUT is selected REASON is
selected
Row 2 has no item STIN is selected STOUT is selected REASON is
selected
Row two or row 3 with no item must be checked and all the other available rows must be checked when the generate xml button is clicked.
<?php
while ($row = sqlsrv_fetch_array($result)) {
$S1 = $row['Qty_ExchangeStock'];
$S2 = $row['Qty_InService'];
$S3 = $row['Qty_TotalStock'];
$status = '1';
$Stock = $S1 - $S2;
if ($Stock < 1) {
$status = '2';
$Stock = 0;
}
echo '<tr>';
echo '<td><input type="text" name="SONR-'.$counter.'" value="'.$row['No_'].'" size="6" readonly /></td>';
echo '<td><div>'.$row['Brand']. '</div></td>';
echo '<td><div>'.$row['Model']. '</div>';
echo ' <input type="hidden" name="SIGC-'.$counter.'" value="'.$row['Service Item Group Code']. '" /></td>';
echo '<td><input type="text" name="ITEM-'.$counter.'" value="'.$row['Item No_'].'" size="8" readonly /></td>';
echo '<td class="center"><div>'.$Stock. '</div></td>';
echo '<td class="center"><div>'.$row['Claim']. '</div></td>';
echo '<td><input type="text" class="small" maxlength="20" placeholder="Serienummer" name="SNR-'.$counter.'" /></td>';
echo '<td><input type="text" class="small" maxlength="10" placeholder="Approval NR" name="APPNR-'.$counter.'" /></td>';
echo '<td><select id="check" name="STIN-'.$counter.'" class="small">'.$ruilin.'</select></td>';
echo '<td><select name="STOUT-'.$counter.'" class="small">'.$ruiluit.'</select></td>';
echo '<td><select name="REASON-'.$counter.'" class="small">'.$dropdown.'</select></td>';
echo '<td><input type="text" maxlength="70" title="Opmerking: maximaal 80 tekens" name="OPM-'.$counter.'" /></td>';
echo "</tr>\r\n";
$counter++;
}
?>
</tbody>
</table>
<input type="submit" value="Generate XML">
</form>
</div>
</div>
<?php
}
?>

You probably want to start off with server-side validation. The reason is people can turn off validation or use scripting to make calls and you need to be able to validate the logic properly on the server.
In this case you need to define a server-side API (what data does the server have to know?), check and document it. But that starts with design and I don't think you are there yet.
Once you have that done you can add similar checks in Javascript. This improves user experience but it is no replacement for server-side checks.

Related

How to post multiple entries from dynamically generated textboxes in while loop

please i am currently working on a school result computation project in php. I have a page that gets all the students that enrolled for a particular subject. A while loop generates three textboxes against each student's name(CA1, CA2, and Exam). Please can anyone help me with a solution?? When the form is submitted only the last entry enters the database. Below is my code.
<?php
session_start();
include 'header_staff.php';
$subject=$_POST['subject'];
$user_id=$_SESSION['user_id'];
$get=mysql_query("SELECT * FROM staffrecord WHERE user_id='$user_id'",$conn);
$go=mysql_fetch_array($get);
$class=$go['class_id'];
$sql=mysql_query("SELECT * FROM student_enrollment WHERE class_id='$class' AND subject_id='$subject'",$conn);
echo '<form action="submitrslt.php" method="post">';
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1" />';
echo '<input type="text" name="ca2" />';
echo '<input type="text" name="exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
?>
The solution to your problem is to use your input arrays by simply adding [] to the input names:
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[]" />';
echo '<input type="text" name="ca2[]" />';
echo '<input type="text" name="exam[]" /><br><br>';
}
Further, you can use the primary key of your table as the index in each iteration (let's suppose this would be $subj['id'], but if it is more meaningful in your case, you can also use $subj['name'] as the index):
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="ca2[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="exam[<?php echo $subj['id'] ?>]" /><br><br>';
}
This way you can easily identify values from the resulting array after the post.
PS: Be sure you never trust user input without verifying or sanitizing it - make sure $_POST['subject'] is numeric. You can find plenty of useful tips on how to achieve this.
I have added comments, this will solve your problem i am assuming your subjects data is unique for the loop. And i have defined the input with the subject name which make it unique. Just for an example you can try your own method. This will output all the post variables on your action(form post) screen.
<?php
while($subj=mysql_fetch_array($sql)){
$subname = str_replace(' ','', $subj['name']); //just to replace the space
echo $subj['name'];
echo '<input type="text" name="'.$subname.'_ca1" />'; //to make the field unique for the input entries
echo '<input type="text" name="'.$subname.'_ca2" />';
echo '<input type="text" name="'.$subname.'_exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
echo '</form>';
?>
Firstly, I would suggest changing the connection to mysqli, which follows a very similar syntax to mysql except that it is not deprecated.
Secondly, the form looks fine, except that the textboxes and submit button don't have any unique identifiers, you might try putting in a unique 'id' for each of the input fields. Since your loop is combining all input fields in one form, this is likely the culprit. Furthermore, I don't see a closing tag for form, i.e. </form>.
Finally, you should look up filter_input for handling superglobals such as $_POST[].
I assume that all fields are meant to be submitted at once rather than individually?

Radio Buttons / Checkboxes

I wasn't sure how to word the title, because just thinking about this concept kind of confuses me and I'm not sure why. I'm sure there is some simple solution to this.
Here is a picture of my codes (Attached below) output.
The user should be able to click 1 radiobox inside each box, but I can't seem to make it do that. The way it is right now, only 1 vacation button can be selected and only 1 absent button can be selected.
Here is my code:
if($loop < 4) {
echo '<td>';
echo ' NAME<BR><input type="radio" name="vacationTeammates[]" value="'.$value[0].'">Vacation<br>
<input type="radio" name="absentTeammates[]" value="'.$value[0].'">Absent';
echo '</td>';
$loop++;
} else {
$loop = 1;
echo "</tr><tr align='center'>";
echo '<td>';
echo ' NAME<BR><input type="radio" name="vacationTeammates[]" value="'.$value[0].'">Vacation<br>
<input type="radio" name="absentTeammates[]" value="'.$value[0].'">Absent';
echo '</td>';
}
(The loop makes it so that the table row ends and starts a new one, so it is somewhat irrelevant but the radio buttons are what matters)
Each radio button pair must have the same "name" attribute value for browsers to know they're their own set.
Change your code to something like this, where "$SomeUniqueRowVar" is a variable that changes for each row:
echo 'NAME<BR>';
echo '<input type="radio" name="status'.$SomeUniqueRowVar.'" value="vacation">';
echo 'Vacation<br>';
echo '<input type="radio" name="status'.$SomeUniqueRowVar.'" value="absent">';
echo 'Absent';
I would add a counter and assign each name to a specific array element, rather than just []. Since you only want one of the radios to be selectable for each teammate, the inputs will have to be the same name but have different values. Put the teammates name in an array (a variable separate from the radio inputs) that uses the counter as it's index. This way you know which response goes to which teammate.
if($loop < 4) {
$name[$counter] = $value[0];
echo '<td>';
echo ' NAME<BR><input type="radio" name="teammates[$counter]" value=1>Vacation<br>
<input type="radio" name="teammates[$counter]" value=0>Absent';
echo '</td>';
$counter++;
$loop++;
} else {
$name[$counter] = $value[0];
$loop = 1;
echo "</tr><tr align='center'>";
echo '<td>';
echo ' NAME<BR><input type="radio" name="teammates[$counter]" value=1>Vacation<br>
<input type="radio" name="teammates[$counter]" value=0>Absent';
echo '</td>';
$counter++;
}
Now when you process the array, you will know if teammates[$counter] is 1 it means vacation and 0 it means absent.
You could also opt to use the name AS the index if you can be sure it is free of special characters/safely parse special chars out.
Thank you #user3163495 & #FirstOne for a few tips I used in my answer here.
I made both of the radio buttons in each cell have the same name, and all the others have different names.
if($loop < 4) {
echo '<td>';
echo ' <input type="radio" name="goneTeammates['.$uniqueLoop.']" value="'.$value[0].'|V">Vacation<br>
<input type="radio" name="goneTeammates['.$uniqueLoop.']" value="'.$value[0].'|A">Absent<br>NAME';
echo '</td>';
$loop++;
} else {
$loop = 1;
echo "</tr><tr align='center'>";
echo '<td>';
echo ' <input type="radio" name="goneTeammates['.$uniqueLoop.']" value="'.$value[0].'|V">Vacation<br>
<input type="radio" name="goneTeammates['.$uniqueLoop.']" value="'.$value[0].'|A">Absent<br>NAME';
echo '</td>';
}
For the value, I used the teammates name (Actually their uniqueid) and an A for absent or V for vacation. The output would basically look like:
35|A
23|V
64|A
etc
On the processing side I explode()'d the input at that | sign, to basically get the uniqueID and the letter in seperate variables, and processed like normal from there.

PHP generate multiple form fields

I am working on a system to edit/create an online food menu.
On the system that creates/edits the menu I would like the user to be able to enter a new item and price in two form fields and then press 'add another item' in turn this generates another form field. The user can keep pressing 'add another item' or simply submit the form.
Ideally it would keep generating forms fields then when the form is submitted an I handle the POST array and do the DB work.
I'm just not too sure on how I can allow the user to essentially keep adding form fields.
This is system is currently written in PHP.
Hi, Looking into this and my current code, this issue I see is that the form itself is also dynamically generated from database results. Your idea I can see working when I create an entirely new menu, but what if I want to edit a current menu and add a new item to it.
This is the code that generate the current form.
if($menuItems->count()) {
echo '<form class="updateMenu" action="" method="post">';
echo '<table class="gridtable gridtableMenu">';
echo '<tr><th>Item Name</th><th>Item Price</th></tr>';
foreach($menuItems->results() as $item){
echo '<tr>';
echo '<td class="menu-name"><input type="text" name="itemName[]" value="' . $item->item_name . '" required></td>';
echo '<td class="menu-price"><input type="number" step="any" name="itemPrice[]" value="' . $item->item_price . '" required></td>';
echo '<input type="hidden" name="id[]" value="' . $item->id . '">';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="updateMneu" value="Update Menu">';
echo '</form>';
} else {
echo '<div class="error">No items have been added to this menu</div>';
}

How to change Shopping Cart from updating one item to updating them all

It took a long time but I got a shopping cart working. The thing is, in the nature of my business a customer could have hundreds of things in their cart, and the way I'm updating individual items is pretty primitive and can get tedious if there is a lot of items that needs updating.
For each row in the shopping cart database for a customer's cart, I generate the item's form and product information. Each row therefore has it's own Update Item button.
$top_query = "SELECT t1.product_id, image_path, suggested_quantity, sales_info sku_item_number FROM product_customer_suggested_qty AS t1
LEFT JOIN product_images AS t2 ON t1.product_id = t2.product_id
RIGHT JOIN products AS t3 ON t1.product_id = t3.product_id
WHERE customer_id = '".$customer_id."'
AND cart_visible != 0";
//echo $top_query;
$histresult = mysql_query($top_query) or die (mysql_error());
<tr>
<td width="181"><strong>Product</strong></td>
<td width="181"><strong>Sales Info</strong></td>
<td width="100"><strong>Suggested Qty</strong></td>
<td width="100"><strong>Qty</strong></td>
<td width="100"><strong>Image</strong></td>
<td width="100"><strong>Add to Cart?</strong></td>
</tr>
<?php
$i =0;
while($row=mysql_fetch_array($histresult))
{
echo '<tr height = "50px">';
//We grab the product id as well as everything else we need.
$customer_id= $row['customer_id'];
$product_id= $row['product_id'];
$link = $row['image_path'];
$sku_item_number = $row['sku_item_number'];
$suggested_quantity = $row['suggested_quantity'];
echo '
<form action="ezcopy.php? method="post"><td>'.$sku_item_number.'</td>';
echo '<td>'.$suggested_quantity.'
<input class="same" id="same'.$i.'" title="'.$i.'" name="same'.$i.'" type="checkbox" value ="'.$suggested_quantity.'"/>
<input name="customer_id" type="hidden" value="'.$customer_id.'">
<input name="product_id" type="hidden" value="'.$product_id.'">
<input name="i" type="hidden" value="'.$i.'">
</td>';
echo '<td><input class="qty" name="qty'.$i.'" id="qty'.$i.'" type="text"size="4" maxlength="4"></td>';
This is just a piece of the entire row, and it functions fully for both updating quantities, and allowing the user to automatically copy suggested values based on their history.
But if I want to make just one button on the bottom that says "Update All," and therefore make the entire shopping cart one large form, how do I modify the quantity form so that it can read in an unknown, dynamic number of items and update the database? What's a good strategy for achieving that?
After much struggling with Google, I finally found an example here.
http://www.theblog.ca/update-multiple-rows-mysql
The key is changing the form to one large one rather than many small ones, outside the row generating loop.
while($row=mysql_fetch_array($histresult))
{
echo '<tr height = "50px">';
//We grab the product id as well as everything else we need.
$customer_id= $row['customer_id'];
$product_id= $row['product_id'];
$link = $row['image_path'];
$sku_item_number = $row['sku_item_number'];
$suggested_quantity = $row['suggested_quantity'];
$sales_info = $row['sales_info'];
$item_id = $row['id_product_customer_suggested_qty'];
echo '<td>'.$sku_item_number;
//This array stores the item index.
echo '</td>';
echo '<td>'.$sales_info.'</td>';
echo '<td>'.$suggested_quantity.'
<input class="same" id="same'.$i.'" title="'.$i.'" name="same'.$i.'" type="checkbox" value ="'.$suggested_quantity.'"/>
<input name="item_id[]" type="hidden" value="'.$item_id.'">
<input name="customer_id[]" type="hidden" value="'.$customer_id.'">
<input name="product_id[]" type="hidden" value="'.$product_id.'">
<input name="i" type="hidden" value="'.$i.'">
</td>';
echo '<td><input class="qty" name="qty[]" id="qty'.$i.'" type="text"size="4" maxlength="4"></td>';
The first key is how the input names have changed. They are now all arrays. At the end of the row generating loop is a submit button. Then, what happens upon submit is the next key.
foreach($_POST['item_id'] as $key=>$item_id)
{
$qty = $_POST['qty'][$key];
$product_id = $_POST['product_id'][$key];
$customer_id = $_POST['customer_id'][$key];
if (!empty($qty))
{
echo 'Product is '.$product_id.'<br>';
echo 'Quantity requestesd is '.$qty.'<br><br>';
//perform UPDATE query as that inidividual item
}
}
This dynamically grabs every existing row in the form, each one made unique by the item_id. We can now perform update queries, only as needed. This is a really powerful trick.

PHP: using post when mutliple form fields share same name & id

That title probably doesn't mean much but what I have is a form that is generated dynamically. I hooks into a table of products, pulls out there name. I then create a form that displays the product with a checkbox and textbox next to it.
<form id="twitter-feed" name="twitter-feed" action="<?php echo $this->getUrl('tweet/') ?>index/tweet" method="post">
<table><tr>
<?php
$model = Mage::getModel("optimise_twitterfeed/twitterfeed");
$products = $model->getProducts();
foreach ($products as $product){
echo '<tr>';
echo '<td>';
echo '<label for="'. $product .'">' . $product . '</label>';
echo '<br /><input type="text" class="hashtag" name="tags" id="tags" value="#enter, #product, #hastag"';
echo '</td>';
echo '<td><input type="checkbox" name="chk" id="'. $product .'"></td>';
echo '</tr>';
}
?>
<tr><td colspan="2"><input type="submit" name="submit" value="tweet"></td></tr>
</table>
</form>
As you can see there are checkboxes and textfields for each record. When I examine the $_POST data from the form it only retains fields for the last record.
Is there a way to pass all this data back to the action?
Cheers,
Jonesy
Use name="chk[]", then PHP will create an array for you.
Change your name arrtibutes to have an opening and closing square brace like this:
name="tags"
name="chk"
to
name="tags[]"
name="chk[]"
This will turn an array like:
$_POST['tags'][0] = VALUE
$_POST['tags'][1] = VALUE
$_POST['chk'][0] = VALUE
$_POST['chk'][1] = VALUE
Yes you can, set brackets at the end of the name value.
E.g.:
<input type="checkbox" name="chk[]" id="'. $product .'">
Then you get an array as result in $_POST['chk'].
Besides that, ids should always be unique. You can give same names, but you should always use different ids.
All of your fields have the same name, when that happens on any form you end up only seeing the last value because it's overwritten by the other fields.
Instead of <input type="checkbox" name="chk" id="124123"> do something like <input type="checkbox" name="chk[124123]" value='1'>
In your code you'd receive $_POST['chk'] as an array of values, only those values that were checked.
you can use as i have given example below. where i have taken one new variable $i = 0; and then you can use this $i into the foreach loop for displaying all product one-by-one..
i think this may help you.
$i = 0;
foreach ($products as $product){
echo '<td><input type="checkbox" name="chk" id="'. $product[$i] .'"></td>';
}

Categories