I want to above Master and child system by using PHP,MYSQL & JQuery.
I am attaching sample image link below See screenshot
Product Quantity and UOM is field which belong to MAster Table and
Code, Component, category, quantity (Also) & UOM (duplicate) is belong to Child table.
I want to add Code, Component, category, quantity etc multiple time whenever user click on add.
Just need to know how can i save all these multiple records when someone completed their works and click on Final Save Button?
I am really and very aggressively searching for this but didn't get any anwer.
If anyone who can find the way or any help or anything that will help me towards this system.
Thanks a lots pls pls Help
you'll want to use
jQuery ajax to save data
.clone() to add a record in the UI you'll have to reset the values will your at it
that should get you started
Each time your user clicks 'add' you want to take the values of your form inputs, build a new table row and show their selected values. This is easy enough, but you also need to add hidden inputs which represent what they chose in the select boxes above, so when the user clicks save, the whole form is posted and you can process the input. A simple example would be:
<script>
var count = 0;
$('#add').click(function(event)
{
var code = $('#code').val(),
component = $('#component').val()
category = $('#category').val(),
uom = $('#uom').val();
$('#table').append(
'<tr>'
+ '<td>' + code + '<input type="hidden" name="record[' + count + '][code]"></td>'
+ '<td>' + component + '<input type="hidden" name="record[' + count + '][component]"></td>'
+ '<td>' + category + '<input type="hidden" name="record[' + count + '][category]"></td>'
+ '<td>' + uom + '<input type="hidden" name="record[' + count + '][uom]"></td>'
+ '</tr>'
);
/*
EDIT: I changed this to a DECREMENTOR so our keys don't overlap and override
anything that is CURRENTLY in the database
*/
count --;
})
</script>
This would attach a click handler to the add button. Each time it is clicked, we get the values of the inputs, store them in a variable, and build + append a new table row to your "preview table" below, which shows the values they selected and creates hidden inputs which can be processed later after the user clicks Save.
Some notes about this:
- it only gets the value of the selected inputs (so for the select boxes, the value of the option not the text. you'll have to do some extra work to replace that into your table row.
- your entire table will have to be encapsulated in a <form> tag, which your save button must also be inside.
Once you get the posted data to the server, do a print_r($_POST) to see what it looks like, you should be able to figure out how to process it fairly easily.
edit
Okay, so you asked a lot of questions here, i'll try to address them as best I can, without writing a novel.
What if someone mistakenly clicks on add and wants to cancel the addition (or changes their mind, whatever).
This actually isn't that hard. If this happens, just remove the appended table row from your table using $.remove. Since all the hidden input elements are contained within the table row, they will also be removed from the form so when the user posts, the fields will not be present.
How should you sanitize the data?
Sanitize the data when the user clicks add, as you populate the form, instead of afterwards, just before you post the form. It will be easier to deal with the input errors when the user clicks add than it will be to deal with them when they click save.
How can you use this method if you want to modify existing records in the database?
There's a few different ways you can handle this. The easiest way is to pre-populate your form with table rows for each existing row in your database, and add an id (assuming you have an auto-increment primary key for each row) input value for that record on the table row. This way when you're processing the form, you'll be able to see if it's an existing record by checking for the existence of the id in the posted data and verifying that it exists in your database. If it doesn't have an id key you know that it is a new record and you need to do an INSERT, and if it does, you can do an UPDATE or leave the record be. For DELETED rows, you'll want to loop through your POSTed data before doing any INSERTs and gather the id values that have been posted and run a query something like DELETE FROM table WHERE ID IN (<list of posted ids>). This will delete any rows that the user removed, then you can loop through the POSTed data again and insert the new rows.
An example of pre-populating this table would look something like this:
<?php
$query = "SELECT * FROM bill_items WHERE bill_id = 123";
$result = mysql_query($query);
$materials = array();
while ($row = mysql_fetch_assoc($query))
{
$materials []= $row;
}
?>
<? foreach ($materials as $material): ?>
<tr>
<td>
<?= $material['code']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][code]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['component']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][component]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['category'];
<input type="hidden" name="record[<?= $material['id']; ?>][category]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['quantity']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][quantity]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['uom']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][uom]"
value="<?= $material['uom']; ?>">
<input type="hidden" name="record[<?= material['id']; ?>][id]"
value="<?= $material['id']; ?>">
</td>
</tr>
<? endforeach; ?>
Also, a note. I changed the javascript example code above. I changed count++ to count-- because when you pre-populate the form with data that is currently in the database you are going to use the id of the material in the input key. When a user adds new data, there is a possibility that the key generated with javascript (with count++) will collide with the existing table data. To rectify this, we change it to count--. This key (in javascript) really isn't important, it's just keeping our data grouped together, so a negative value here does not affect anything.
Related
Long time listener, first time caller. I am implementing a system to track who participates in various events. After defining the "activity" record, the plan is to populate another table with the list of members (lets say 60) who might have attended, then present a form for the organizer to 'check' who actually participated with the hours spent. This information is then passed by POST to update the database.
The issue deals with the array of Checkboxes, one for each participant, and correct handoffs to the DB update process. The problem is that the first time a checkbox is changed, either manually by the organizer or automatically to reflect a previous choice, it generates an extra element in the checkbox array, thereby throwing them all out of alignment with the other arrays. This link (Do checkbox inputs only post data if they're checked?) was the closest to the problem that I found, but did not address handling checkbox arrays.
I implemented the hidden checkbox approach per several posts, tried both absolute array indexing, and am I still get an extra array element every time. I even contemplated replacing the checkboxes with something less elegant like 2 radio buttons (Y/N) each or a two-value select field. I am definitely not an expert here and am willing to do the research and learn, but I've hit a dead-end.
Any ideas, workarounds, or links to other references for this would be appreciated.
Here is the code:
<?php
echo "<form action=\"index.php\" method=\"post\">";
$query = ((get stuff));
$result = mysqli_query($con, $query) or die ('Sorry, could not access the joined users+activitypart tables');
// extract and format all users for the activity
$i = 0;
while($row=mysqli_fetch_array($result, MYSQL_ASSOC))
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$apidx[] = $row['apidx']; // Pointer to this user's record
$isParticipant[] = $row['isParticipant']; // checkbox value
$actduration[] = $row['actduration']; // Actual duration in hours spent
$role[] = $row['role']; // Role that this person held during this activity
?>
<input type="hidden" name="passidx[]" value="<? print $apidx[$i] ?>">
<input type="hidden" name="passpart[<? $i ?>]" value="0" />
<input type="checkbox" name="passpart[<? $i ?>]" value="1" <? if($isParticipant["$i"]) print "CHECKED" ?> />
<input type="text" name="passdura[]" size="7" value="<? print $actduration["$i"] ?>">
<?php
echo "$i $firstname $lastname<br>";
$i++;
}
?>
<!-- when done, pass all name field values to actusr08a -->
<br><input type="hidden" name="content" value="actusr08a">
<span class="form-field-no-caption">
<input type="submit" value="Submit">
</span>
</form>
So, When I load this page with 15 members, as a debug step, I count the 3 arrays and they all show 15, 15, 15 elements each at load time. If I click on 2 check-boxes, post it to the next page and do a count of the received arrays, two of the arrays (passidx, passdura) show 15 elements each, and the checkbox array (passpart) shows 17. since 2 checkboxes changed, seems they then post the change, thus the additional 2 elements. This is what I am trying to fix.
The newbie is back with another question. Any help would be much appreciated. Suppose we have got a form in which we have written down the name of a user and in front of which there is an input box in which we can allocate a grade to the mentioned user. Within this scenario, everything is clear. We have a form with the name of user (it's 'id' as the value) and another variable, that is the grade' which are posted to the php-action-page. Hence, in the php-action-page, I get two variables, one is the id of the user and the other allocated grade, through POST. Here, everything is clear and the process easy, since I have got just two defined variables. Now, suppose that we are inserting a list of users from our 'Users' table into the form dynamically. We fill our form with for example 10 users grabbed from the database. In front of them there are input boxes for the 'grade' to be inserted into. So far, everything is fine. The problem, though, lies in the next stage. The problem is I don't know how to ask php-action-page to do the insert, that is insert the grade in the database for specific users as long as there are posted variables of users. Here I have tens of users and tens of dynamic variables. And if the question is a little bit vague, please do excuse me; yet, do your best to get me free from this condition of bafflement. Many thanks.
Here comes some bits of the code to make the problem a little more clear.
I start with the following code:
<?php
require_once ('../inc/takein.php');
$pd = new dbase();
$students = $pd->run_a_query('SELECT * from `checking`');
Here I am including the database and other necessary files. Then I run a query to fetch a list of my students from the table. So far, everything is fine. The next line of action which makes me perplexed is the following code.
Before having a look at the code may you please look at the html design in the following picture:
Final Design
I totally have no idea about it being wrong or correct. You might help with this bit as well.
<form action="grades.php" method="post">
<table class="table table-bordered font-label" id="item_table">
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade[]" class="form-control omit-radius-input"></td>';
echo '<input type="hidden" name="id[]" value="'.$student['id'].'">';
echo '<tr>';
}
?>
</table>
<input type="submit" name="dispatched" class="btn btn-green">
</form>
Here, I am putting the information in a table within the form element. As you can see in the above picture, I am getting four students from the database. Now I want to send these students back to the database along with their newly set grades. What I want to be posted here is the student id and their grades.
Then, the following is the last part of the code which is left incomplete because I couldn't make any senses how to do it.
if (isset($_POST['dispatched'])) {
$id[] = $_POST['id'];
$grade[] = $_POST['grade'];
// what to do now???!!!
foreach(...HOW TO DO THE 'FOREACH') {
...
}
}
May you please help me insert my student grades. Many thanks in advance.
Simply name your variables as arrays - if your form looks like this
<form method="POST">
<input type="text" name="grade[12]">
<br>
<input type="text" name="grade[15]">
<br>
<input type="text" name="grade[7]">
<br>
<input type="text" name="grade[21]">
<!-- continue here -->
</form>
then in your PHP code you will access the grades like this
if(is_array($_POST['grade'])) foreach($_POST['grade'] as $id => $value)
{
// REPLACE INTO user_grades(user_id, grade) VALUES($id, $value)
}
UPDATE
You should also put the ID of your students in the name of the INPUT field - otherwise you won't know for which student is the given grade.
<?php
foreach ($students as $student) {
echo '<tr>';
echo '<td>'.$student['name'].'</td>';
echo '<td><input type="text" name="grade['.$student['id'].']" class="form-control omit-radius-input" value="'.$student['current_grade'].'"></td>';
echo '<tr>';
}
?>
The foreach is shown above in my original answer.
I am currently working on an update profile section of a website I am creating for fun. In this part of the update profile business owners can update their restaurant menu (menu consists of category (appetizers, entrees, etc), menu item and allergens).
Right now the website is printing out what the business owner has previously submitted in input box format, this way business owners can simply just erase and re-enter their new information. However, we don't know exactly how many menu items each restaurant has so I devised a system to dynamically update each item being altered row by row.
<?php
$sql="SELECT * from menu_item as m, allergen as a WHERE a.restaurant_id=m.restaurant_id AND m.menu_item_id=a.menu_item_id AND m.restaurant_id='".$rest_id."'";
$result11=mysqli_query($con,$sql);
if (mysqli_num_rows($result)==0){
echo "<strong>You have not submitted any menu information</strong><br><br>";
echo "Please enter your menu information here: ";
echo 'Create Menu';
}
else{
$i=0;
echo "<table border='1' cellpadding='10'><tr><th>Category</th><th>Menu Item</th><th>Allergen</th></tr>";
while($rows=mysqli_fetch_assoc($result11)) {
echo '<tr><td><input type="text" name="category'.$i.'"value="'. $rows['category']. '"</td><br>';
echo '<td><input type="text" name="menu_item'.$i.'" value="'. $rows['menu_item']. '"</td><br>';
echo '<td><input type="text" name="allergen'.$i.'" value="'. $rows['allergen']. '"</td><br>';
echo '<td><input type="hidden" name="id'.$i.'" value="'. $rows['menu_item_id']. '"</td></tr><br>';
$i++;
}
}
echo "</table>";
var_dump(mysqli_num_rows($result11));
// var_dump($_POST);
$count=0;
while ($count<=mysqli_num_rows($result11)){
${"category".$count}=mysqli_real_escape_string($con, $_POST['category'.'$count']);
$count++;
}
var_dump($category0);
?>
This is where the while loop near the bottom comes into play. I want to be able to dynamically create variables for category, menu item, and allergen. Then I want to be able to create $result variables within this same while loop (mysqli_query) and then update rows accordingly. However, right now my very last var_dump is returning a value of "" which tells me I'm either concatenating the html name attribute wrong(first while loop) or there is something wrong with concatenation in my last while loop. Does anyone know what I'm doing wrong?
$_POST['category'.'$count'] in your second loop should be $_POST['category'.$count]. You also only want to run this code after the form has been submitted (I'm assuming the code you've posted is not your full script so it's not clear if that's what is happening) - otherwise you'll get the original values rather than any changes the user has made in the form.
In general you'll have an easier time if you can get the submitted data into a multi-dimensional array which you can loop through, instead of having to dynamically create variables. See the section "How do I create arrays in a HTML form?" on http://php.net/manual/en/faq.html.php. In your case I'd do something like:
// (in your first while loop)
echo '<input type="text" name="menu['.$i.'][category]" value="'. htmlspecialchars($rows['category']). '"><br>';
echo '<input type="text" name="menu['.$i.'][menu_item]" value="'. htmlspecialchars($rows['menu_item']). '"><br>';
// (etc.)
You then loop through this with something like:
foreach ($_POST['menu'] as $menuRow) {
// you now have:
// $menuRow['category']
// $menuRow['menu_item']
// ...and so on
}
You also want to escape the input values you are outputting with htmlspecialchars() as I have above.
So, my webpage has a html-table which displays rows with one item pr. row including various data regarding that item in the columns.
The table is populated using mysqli call to db. So far so good.
Excerpts of the table look like this (I've tried to only show the "important" parts of the code to avoid cluttering - there 8 more text fields similar to "nytAntalGangeUdfoert" for each item)
<td><input type="text" name="nytAntalGangeUdfoert[]" value="<?php echo $antalGangeUdfoert ?>"></td>
<?php if ($aktivStatus == 1) { ?>
<td><input type="checkbox" name="nyAktivStatus[]" value="<?php echo $aktivStatus ?>" checked="checked"/></td>
<?php } else { ?>
<td><input type="checkbox" name="nyAktivStatus[]" value="<?php echo $aktivStatus ?>" /></td>
The text field(s) works fine in all aspects.
For the checkbox, the if-else part decides whether the checkbox should be displayed as checked (active or not) dependent on the value in my db-table (1 or 0) This works fine.
I then have 'duplicate' hidden fields to log the original status of the checkbox for later comparison after posting:
<td><input type="hidden" name="antalGangeUdfoert[]" value="<?php echo $antalGangeUdfoert ?>"></td>
<td><input type="hidden" name="aktivStatus[]" value="<?php echo $aktivStatus ?>"></td>
All of this is posted to another page where it is handled as follows (again, only excerpts of the full table). 'aktivstatus' is the old status from db, and 'nyaktivstatus' is the one posted (i.e. the one selected by the user via the checkboxes - can of course be the same as original state)
if(isset($_POST['submit']))
{
$antalGangeUdfoert = $_POST["antalGangeUdfoert"];
$nytAntalGangeUdfoert = $_POST["nytAntalGangeUdfoert"];
$aktivStatus = $_POST["aktivStatus"];
foreach( $navn as $n => $n )
{
if(isset($_POST["nyAktivStatus"][$n])) {
$nyAktivStatus[$n] = 1;
} else {
$nyAktivStatus[$n] = 0;
}
if( $antalGangeUdfoert[$n] <> $nytantalGangeUdfoert[$n] || $aktivStatus[$n] <> $nyAktivStatus[$n]) {
//run function to update items where a change has been made by the user)
As stated earlier, the above approach works fine for all the text fields, but in some cases, the new state of a checkbox is saved for the wrong item, apparently (changes to the text fields are correctly saved in db regardless)
Examples below:
Row---status when fetched---user input---saved as
Row1: 1-->0-->1 ERROR
Row2: 1-->1-->1 OK
Row3: 1-->1-->0 ERROR
Row1: 1-->1-->1 OK
Row2: 1-->1-->1 OK
Row3: 0-->1-->1 OK
Row1: 1-->0-->0 OK
Row2: 1-->0-->0 OK
Row3: 1-->0-->0 OK
Row1: 0-->1-->1 OK
Row2: 0-->1-->1 OK
Row3: 0-->1-->1 OK
Row1: 1-->0-->1 ERROR
Row2: 1-->0-->0 OK
Row3: 1-->1-->0 ERROR
FYI at one point, I changed the checkbox into a textfield and manually entered 1 or 0, and this worked fine...not ideal solution, though...
So, I guess there's something going wrong when posting/assigning the "nyaktivstatus' (user entered status)
Can anyone spot the issue in my code? Or spot a pattern that I'm not seeing?
Thanks!
$aktivStatus may not be set at all if the checkbox was not ticked.
Right where you have $aktivStatus = $_POST["aktivStatus"]; try replacing it with:
if (!array_key_exists('aktivStatus',$_POST))
$aktivStatus = 0;
else
$aktivStatus = $_POST["aktivStatus"];
This way if the checkbox was not set and the browser did not POST it at all, your variable will assume 0, otherwise it'll assume the value POSTed by browser.
As the unchecked checkboxes are not carried on post,in this case we might use a little javascript to take the value of checkboxes to a corresponding hidden text box on the on change event of the checkbox. here's a sample javascript to keep on the same page as my form below. This code is a demonstration on how to achieve the questioners target. Could be possible other ways to achieve this. Sessions could also be used on some parts.
<script type="text/javascript">
function changed(id){
var checkBoxValue=document.getElementById(id).value;
id=id.replace('checkbox','');
hTextBoxid='hidden['+id+']';
var hiddenTextBox=document.getElementById(hTextBoxid);
hiddenTextBox.value=checkBoxValue;
}
</script>
Here's the form
<?php
//uncomment for debugging
//if(isset($_POST)){
//for debugging could use this to see the variables that were passed on form submit
//echo '<pre>'; print_r($_POST); echo'</pre>';
//on post of data remember to sanitize and do the checks here server side.
//as we used javascript on the form for checkboxes and hidden text box should varify those post data on server side here.for example whether the check box array count and value matches..
//;}
?>
<form action="" method="post" enctype="application/x-www-form-urlencoded">
<table>
<tr>
<?php
//sample data as if it came from db
$antalGangeUdfoert=array('a','b','c','d','x','y','z');
//sample data as if it came from db
$aktivStatus=array(0,0,1,0,1,1,0);
?>
<?php
$i=0;
//could use a for loop after counting the fetched rows,
//could use other than $aktivStatus, i used $aktivStatus here
foreach($aktivStatus as $aktivStatus){
echo '<td><input type="text" name="nytAntalGangeUdfoert['.$i.']" value="'.$antalGangeUdfoert[$i].'"></td><td>';
//check whether its checked depending on activeStatus
$aktivStatus[$i] == 1? $check='1':$check="0";
//and according to check draw a check box and a hidden text for each
echo '<input type="hidden" id="hidden['.$i.']" name="nyAktivStatus['.$i.']" value="'.$check.'"/>
<input type="checkbox" id="checkbox'.$i.'" value="'.$aktivStatus[$i].'" checked="'.$check.'" onChange="changed(this.id);"/>';
$i++;
};
?>
</td></tr></table>
<input type="submit" name="sub" value="sub"/>
</form>
Please see this link
http://thedesigningworld.com/bea
Here's a Small form contains 8-9 fields + a group of checkboxes
I want to save all details in DB + want to display in a table in proper manner, but it not works properly
Here's the code which i used
for($i=0;$i<count($_POST[wert1]);$i++)
{
if($_POST[wert1][$i]!= "")
{
$check1[] =$_POST['wert1'][$i]; } }
$new1=implode(',', $check1);
$result = "INSERT into table1(check1) values($new1)";
$result = mysqli_query($con, $result);
So i've one doubt that for each checkbox row, should i need to define same array name or different like here i used array name as wert1[] for first row
Checkbox values are not transmitted if the box is not checked.
If you have influence, you could put a hidden input field of the same name before the checkbox and the value "0", like:
<input type="hidden" name="checkbox_name" value="0" />
<input type="checkbox" name="checkbox_name" value="1">Some Text</input>
In you example site, you're using array notation, which is basically a good thing. However, you have not given an index so you might not recognize missing elements.