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.
Related
First of all I'll be sincere, I'm a student and I've been asked to do a task that seems impossible to me. I don't like asking questions because generally speaking I've always been able to fix my coding issues just by searching and learning, but this is the first time I've ever been on this possition.
I need to create a php file that contains a form with two inputs that the user fills. Once he clicks submit the website will show on top of it the two values. Till here I haven't had an issue, but here's the problem, the next time the user sends another submission, instead of clearing the last 2 values and showing 2 new ones, now there needs to be 4 values showing.
I know this is possible to do through JSON, the use of sessions, Ajax, hidden inputs or using another file (this last one is what I would decide to use if I could), but the teacher says we gotta do it on the same html file without the use of any of the methods listed earlier. He says it can be done through an Array that stores the data, but as I'll show in my example, when I do that the moment the user clicks submit the array values are erased and created from zero. I know the most logical thing to do is asking him, but I've already done that 4 times and he literally refuses to help me, so I really don't know what to do, other than asking here. I should point out that the answer has to be server side, because the subject is "Server-Side Programming".
Thank you for your help and sorry beforehand because I'm sure this will end up being a stupid question that can be easily answered.
For the sake of simplicity I erased everything that has to do with formatting. This is the code:
<?php
if (isset($_POST['activity']) && isset($_POST['time'])){
$agenda = array();
$activity = $_POST['activity'];
$time = $_POST['time'];
$text = $activity." ".$time;
array_push($agenda, $text);
foreach ($agenda as $arrayData){
print implode('", "', $agenda);
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<label for="Activity">Activity</label><br>
<input name= "activity" type="text"><br><br>
<label for="Time">Time</label><br>
<input name= "time" type="time"><br><br>
<input type="submit">
</form>
</body>
</html>
Your question was not very clear to be honest but I might have gotten something going for you.
<?php
$formaction = $_SERVER['PHP_SELF'];
if (isset($_POST['activity']) && isset($_POST['time'])){
$agenda = array();
//if the parameter was passed in the action url
if(isset($_GET['agenda'])) {
$agenda = explode(", ", $_GET['agenda']);
}
//set activity time
$text = $_POST['activity']." ".$_POST['time'];
//push into existing array the new values
array_push($agenda, $text);
//print everything
print implode(", ", $agenda);
//update the form action variable
$formaction = $_SERVER['PHP_SELF'] . "?agenda=" . implode(", ", $agenda);
}
?>
<html>
<head>
</head>
<body>
<form action="<?php echo $formaction; ?>" method="POST">
<label for="Activity">Activity</label><br>
<input name= "activity" type="text"><br><br>
<label for="Time">Time</label><br>
<input name= "time" type="time"><br><br>
<input type="submit">
</form>
</body>
</html>
SUMMARY
Since you cant save the posted values into SESSION vars or HIDDEN input, the next best thing would be to append the previous results of the posted form into the form's action url.
When the form is posted, we verify if the query string agenda exists, if it does we explode it into an array called $agenda. We then concatenate the $_POST['activity'] and $_POST['time'] values and push it to the $agenda array. We then PRINT the array $agenda and update the $formaction variable to contain the new values that were added to the array.
In the HTML section we then set the <form action="" to be <form action="<?php echo $formaction; ?>
I am having a problem with simple PHP app where a user has to enter a correct answer from a list of available options. And that options are stored in an array. The problem is that i cannot use the options anytime in the script other than the array declaration point. I might sound dumb...and i am, believe me. Lets say this is the array:
$hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");
Now there is a text box in my script and $_POST method is used to submit the form. The correct choice which i have selected is 'Sports'. Now there are 4 possibilities a user might click submit, they are listed below.
A user clicks the submit button without entering any text in the textbox.
A user guesses the wrong choice which is from the $hobbyChoices but not 'Sports'.
A user guesses a choice which is not from the array. i.e anything other than what is in the array.
Finally, the user enters the correct choice that is 'Sports'.
This might seem pretty easy but the problem is that i cant use the names of the hobbies anywhere in the script, as mentioned before, other than the array declaration. Can i please get help? Also, when i tried to do one of the 4 possibilities, i encountered a problem with the uppercase and lowercase. This is seriously getting irritating, any help would be greatly appreciated.
Thanks!
If I am understanding your question correctly, the following is what you are looking for:
<?php
$hobbyChoices = array("Movie","Music","Games","Books","Sports","Sleeping");
if (isset($_POST['answer'])) {
$answer = mysql_real_escape_string($_POST['answer']);
$correct_answer = $hobbyChoices[4];
$response = "Your answer is not one of the answers listed!";
foreach ($hobbyChoices as $value) {
if (strtolower($answer) == strtolower($value) && (strtolower($answer) != strtolower($correct_answer))) {
$response = "You selected the wrong answer from the list of options!";
}
else if (strtolower($answer) == strtolower($value) && (strtolower($answer) == strtolower($correct_answer))) {
$response = "You have answered correctly!";
}
}
print $response;
}
?>
<form name="form" method="post">
<table>
<tr>
<td>What is baseball?
</td>
<td><input type="text" name="answer" />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="submit" />
</td>
</tr>
</table>
</form>
strtolower is a function in php that converts strings to lowercase and would help you compare your two values.
I am building an application which has a dynamic table, everytime you open the page table`s row and columns changes based on data in database.
Each Row is a vendor company each colomn is a Item Title. All these vendors upply the same item, So this table has a textbox in each contains a TextBox so user can type the value, which represents the amount of fruit they want from that supplier. the following is the example.
So what I need to do now is, after entering these values, I'd like to process them through PHP, and then see 4 different reports at the confirm page, example: write the Company name and under that, what they have to supply for each item, then the next company, so on and so forth to the end.
I don't know if i should create different class for each textbox? or ID them!! SHould I Array them? I am confused.. If any of you guys can help, would be wonderful
Thanks a lot
I would suggest you just name the input elements as an array. something like:
<input type="text" name="fruits[company1][apple]">
<input type="text" name="fruits[company1][berries]">
<input type="text" name="fruits[company1][orange]">
<input type="text" name="fruits[company1][bannana]">
<input type="text" name="fruits[company2][apple]">
<input type="text" name="fruits[company2][berries]">
<input type="text" name="fruits[company2][orange]">
<input type="text" name="fruits[company2][bannana]">
or the same thing with the fruit being the first level and company name being second. It is really the same thing and generally just as easy to use either one. Just depends on how you want to loop over the data once you post the form. You might be better off also using ids for the company name and/or the fruit. Just makes it so, for example, company names with a space are still valid.
Using the above form, you can process the data with something like this:
<?php
foreach($_POST['fruits'] as $company=>$row){
foreach($row as $fruit=>$quantity){
if(!is_numeric($quantity) || $quantity < 0){
$quantity = 0;
}
echo "You selected {$quantity} {$fruit} from {$company}";
}
}
I would try creating a multi dim array with the ID of the item as the first dimension. Like this:
<input type="textbox" name="textbox[<?php echo $row['item_id']; ?>]["apple"]" value="<?php echo $row['apple']; ?>" />
Then, in your processing script:
foreach ($_POST['textbox'] as $row)
{
foreach ($row as $key => $val)
{
$q = "update `items` set `apple` = {$val['apple']} where `item_id` = {$key}";
mysql_query($q);
}
}
This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}
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.