Updating Records with a dynamically generated form - php

Hello everyone first time comment here so please forgive my poor formatting, I am currently working on a project and have hit a serious wall. Before I show the code please read what I am aiming for here, it is rather complex.
So the form that creates the data that I am trying to update in MySQL is dynamically generated, so users can add or remove input fields as needed. So there can be any number of fields to update. The initial population of the table works just fine but here is were it gets interesting.
The page I am having trouble with is the page where users review the data that was submitted, and can make changes as they see fit.
So, the data I am using, just for the sake of putting names to faces, are requirements that must be met in order to qualify for an evaluation. There can be any number of these. So I query and return all of the requirements tied to the evaluation, and then loop through them and echo input fields with the values the user originally submitted.
Bellow you can see what I am talking about, so what I need to do is create an array of form elements that I can loop through. I have the Primary Key of the requirment that needs to be updated under the $Baseline_Requirements_ID PHP variable in a hidden input field (text field in code below for testing) so I can target the correct record in the table and update it with the content in text area.
So ultimately, I feel I have to have the names of the fields be arrays so I can target them, get the length of the array, and then update the records within that loop. Only issue is I can not figure out how to generate the array.
Thank you in advance, Zach
<form id="requirments" name="requirments" method="post" action="">
<?php
$Baseline_Requirements = array();
$Baseline_Requirements_ID = array();
$bas_count = 1;
mysql_data_seek($BaselineRequirments, 0);
while ($row = mysql_fetch_assoc($BaselineRequirments))
{
$Baseline_Requirments[] = $row['Requirement'];
$Baseline_Requirements_ID[] = $row['Baseline_Requirement_ID'];
}
$Req_index = 0;
foreach ($Baseline_Requirments as $value)
{
echo "<textarea name='requirment[]'
id='requirment$count' cols='45' rows='5'>";
echo $value;
echo "</textarea>";
echo "<input name='Baseline_Requirement_ID[]' type='text'
value='$Baseline_Requirements_ID[$Req_index]'>";
$bas_count = $bas_count +1;
$Req_index = $Req_index +1;
}

Sorry, what array are you trying to generate? The array of column/field names? Could you not also include a hidden field that holds the index of the field in the order you retrieve it from the database table? Or even use the index as say, field numbering?

Related

How to put MySQL table into session variable and using the table on next page?

I have two PHP pages. On page1 a temporary table is created and filled with data from a mysql database. I am trying to store this table into a $_SESSION variable so that I can put the table onto page2.
Right now this has been my approach:
This is (part) of the code on page1:
ob_start();
session_start();
//Select data from temporary table
$result = mysqli_query($mysqli,"SELECT * FROM table");
//store table into session variable
$_SESSION['fase1result'] = $result;
This is the code on page2:
ob_start();
session_start();
$table = $_SESSION['fase1result'];
echo "<table border='1'>
<tr>
<th>ProductID</th>
<th>ProductName</th>
<th>Fase1</th>
</tr>";
while($row = mysqli_fetch_array($table))
{
echo "<tr>";
echo "<td>" . $row['ProductID'] . "</td>";
echo "<td>" . $row['ProductName'] . "</td>";
echo "<td>" . $row['Fase1'] . "</td>";
echo "</tr>";
}
echo "</table>";
Unfortunately, up until now these scripts return me an error on page2. At this moment, the echoing of the table on page2 is just to test and verify that the table is actually passed on. At a later moment I want to be able to use MySQL queries to further add data to the table. Hope you could help me.
UPDATE:
Error that I'm getting is:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in domain/page2.php on line 32
With line 32 in page2 being:
while($row = mysqli_fetch_array($table))
To better explain my question, I have posted another question which can be found here:
Modifying MySQL table on different pages with scores from a HTML form
On page1 a temporary table is created and filled with data from a mysql database. I am trying to store this table into a $_SESSION variable so that I can put the table onto page2.
That's impossible.
And shouldn't be used anyway.
something wrong with your design. Most likely such a table is superfluous and you don't actually need it at all.
As of the real problem behind this one - better ask another question, explaining the real life task for which you decided to use a temporary table passed between pages.
Responding to your question one by one:
Error you are Getting
The error that you are getting normally is the result of incorrect spelling or reference of table name, field name or any other variable in the MySQL query. In your case, it may be due to incorrect calling/storing your Session Variable. For example,
//Instead of "table", you typed "tabel". This is just an example.
$result = mysqli_query($mysqli,"SELECT * FROM table");
Share your code so that I can try picking up this error. Above is just an example.
Storing values in Session Variable is not Recommended
Suppose your user fills in the form and moves on to the next phase. The data from the first phase is transferred to the second phase via Session Variable. What if the user simply closes the tab and restarts the process? Session Variable will still be set and the previous data may interfere with the new one and can produce unexpected results.
Ideal Solution
It is better to store the values in JavaScript Array and then transfer to the next page by Hidden Input field. Some of the benefits of using this logic are:
Fast Performance
More Secure
Easily Manageable
Reference Code
If you are taking the values from HTML Forms, then it is very simple to have the value in POST. Using the JQuery UI selection, you can add the selected values in a JavaScript Array.
//Declare Global JavaScript Variable on Page Load. This will be at the end of <head>
$(document).ready(function() {
window.fase1result = [];
} );
After this, on each click event where you want to add the data to be taken to the next page, use the following code to add the value to this array.
fase1result.splice(indexOf_to_add, 1, "SelectedValue");
To understand .splice better, click here.
One selection, e.g. clicking on a Div or link, add the value to a fase1result and on submit add the array value to Input Hidden by using the following:
Add a Javascript Function on form's onsubmit.
<form id="myForm" method="POST" action="fase2.php" onsubmit="return fase1Values()">
Add <input type="hideen" name="fase1values_input" id="fase1values_id"> in the form.
Below is the JavaScript onsubmit function just before </body>.
function fase1Values() {
$( '#fase1values_id' ).val( JSON.stringify(fase1result) );
}
Note that JSON.stringify is required in order to set the Array as an input value.
$decode_fase1result = json_decode( $_POST['fase1values_input'] );
Now you have transferred the fase 1 selection data using an Array from Page 1 to Page 2 without storing data in any temporary table.
Hope this answers your question and solves your problem as well.

PHP $_POST is working but not getting value of HTML element

TL;DR version
I have a big form with hundreds of html input elements on it, I made a php array to store all the element names in it. When I run my process.php file it runs through that array using a loop and creates a new array, the key of that array is the name of each element, and the value of that array is the value of each element. I know this code works as element values for text boxes, radio buttons, and drop-down selections work fine. Checkboxes do not have the values put into the array, instead the key and value read the same thing, the name of the element. Why is $_POST giving me the NAME or ID of my checkbox, and not its value?
Full explanation /w code samples:
The problem I am having seems rather unusual to me as from my understanding it goes against how $_POST should work.
In any case I have been developing a travel insurance website for the past year and it is nearing completion. The client wants me to create a version of the form which they can view after people have submitted applications and it will get the values out of the file they select.
My problem is that $_POST is not getting the value of my checkbox elements but rather their name or id (both are identical so I cannot be sure which it is getting). $_POST is successfully getting the value of all radio, text, and drop-down elements, just not checkboxes.
I have a very large array in my process.php file as the form is quite large. What I've done is create an array which has the name of each element I wish to access. Below is a sample of the structure the array follows, it is far to large to post the entire thing here (400 plus elements on form).
$form_data = array
('trav_emer_med_insur',
'trav_emer_single',
'trav_emer_single_date_go',
'trav_emer_single_date_ba',
'trav_emer_single_days',
'trav_emer_annual',
'trav_emer_annual_date_go',
'trav_emer_annual_days',
'trav_emer_extend',
'trav_emer_extend_date_go',
'trav_emer_extend_date_ef',
'trav_emer_extend_date_ba',
'trav_emer_extend_days',
);
This is the code that runs on process.php to create the user data file, which is saved to a protected folder on the server.
// Create user output data
$out_data = array();
$count = count($form_data);
for( $i = 0; $i < $count; $i++ )
{
if(empty($_POST[$form_data[$i]])) {
$out_data[$form_data[$i]] = " ";
}
else {
$out_data[$form_data[$i]] = $_POST[$form_data[$i]];
}
}
//Set variable names for new file
$dir = "/home/imelnick/public_html/getawayinsured.ca/userdata/";
$timestamp=date("YmdGis");
$name = $out_data['txtApp1Name'];
$value = str_replace(" ", "", $name);
$item = $value . "^" . $timestamp . ".txt";
$filename = $dir . $item;
//Put data in file
//Open file for writing
$fileHandle = fopen($filename, 'w') or die("Can't open file");
//Write contents of out_data array to file
foreach ($out_data as $key => $value) {
$fileLine = $key . "\t" . $value . "\r\n";
fwrite($fileHandle, $fileLine);
}
//Close file
fclose($fileHandle);
The first block of names in the array belong to checkboxes and they follow the format of the following:
<input type="checkbox" name="trav_emer_med_insur" id="trav_emer_med_insur_if" value="YES" class="form_elements" onClick="if(this.checked){document.getElementById('trav_emer_med_options').style.display='block';}else{document.getElementById('trav_emer_med_options').style.display='none';}"/>
The onClick statement expands a div containing additional checkboxes which offer further options to the applicant.
My output data array which is created from the form data has the key of each item in the array as the name of the element, and the value of each item in the array the value of the corresponding HTML element.
Upon splitting the array and writing the $key/$value combination the expected value of $_POST[$form_data[0]] (note: $form_data[0] = trav_emer_med_insur) is the value of the above checkbox code, value="YES". However the output in the file reads as follows.
trav_emer_med_insur trav_emer_med_insur
I am quite sure that there is not a problem with the code that processes the form itself as other elements on the form have their values saved perfectly well to the file (radio buttons, text boxes, drop-downs all work). The Checkboxes do not, they refuse to $_POST the value of the HTML element, and simply keep putting out the name twice.
For example, another element in the form not listed in my array sample above named smoked_if is a radio button pair which asks if the applicant has smoked or not. Here is a sample output from a recent application.
As can be seen the desired result of my code is being performed.
smoked_if no
I am at a loss here because not only does this contradict the functionality of $_POST itself but since all other elements on the form have their values posted without issue it tells me there is a problem with checkbox elements and $_POST.
Any assistance is greatly appreciated.
I think your problem might be related to the fact that checkboxes are not posted when they are not checked.
See Post the checkboxes that are unchecked
if you need to get around this behaviour
AS long as the information is inside of the Form tags, it will be passed to the server. With that said, you need to understand that what is sent to the server is the NAME and VALUE of the items.
When you are looking at PHP, you want to submit, and then a string will look like: sample from http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_form_checkbox as well
?vehicle=car&vehicle=truck
In PHP when you post it, the idea is the same but just hidden from the unskilled eyes. To get the values of it in my example:
$vehicle= $_POST["vehicle"];
echo ''.$vehicle; //shows ARRAY
foreach( $item in $vehicle){
echo ''.$item.'\n'; //will iterate through all the vehicle and print them out
}
YOu can also say things like
if(in_array("car", $vehicle)){
echo "there exists a car\n";
}
http://php.net/manual/en/function.in-array.php
Since the checkboxes are posted only if they are checked, you need a workaround for that. I think the most usual fix is to use a hidden input with the same name as the checkbox's and usually 0 as value. And do not forget to put the hidden input before the checkbox :)
This way even if the checkbox is not checked you get the value of the hidden input. If the checkbox is selected the hidden field's value is overwritten in the POST array by the one from the checkbox.

Use dropdown list selection as mySQL query parameter

I had asked a similar question a few days ago but think I was trying to do to much at one time. I am hoping someone can help get me started on this.
I have two drop down lists, one will be populated with years (2012, 2011 etc) and I have some mySQL databases called "db_2012", "db_2011" etc. In these databases are tables representing months.
I would like the user to select a year and then use that selection to query the correct db and return a list of table names which will be used to populate the second drop down list. Then click a button "See Results" to query the selected table and show the results.
I am putting this on a wordpress website and am using a php template file that I created. This is still new to me and what I have so far doesnt work like I want it too, it is basically setup now that you select a year and select a month (not populated from db) and click a button. It makes the query and my table is displayed, but I need this solution to be more dynamic and work as described above. Thanks for the help.
echo '<form action="" method="post">';
echo'<select name="years" id="years">';
foreach($yearList as $year){
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select><br />';
echo '<select name="monthList" id="months">';
foreach($monthList as $month) {
echo'<option value="'.$month.'">'.$month.'</option>';
}
echo '</select>';
echo '<input type=\'submit\' value=\'See Results\'>';
echo '</form'>
$yearList and $monthList are just pre populated arrays. So now from here I want to click the See Results button and query my sql database using the parameters from the drop down selections.
$database = $_POST['yearList'];
$month = $_POST['monthList'];
$wpdbtest_otherdb = new wpdb('Username', 'Password', $database, 'localhost');
$qStr = "SELECT * FROM $month";
$myResults = $wpdbtest_otherdb->get_results($qStr, OBJECT);
It sounds like you want to send an AJAX call to a separate php page for security and processing, then have the PHP return XML that you parse back into the second selection box via the AJAX callback. It can be a little messy, but it allows you to check for weird form values that users might inject.
Edit: The PHP will receive your AJAX parameters as parts of the $_GET or the $_POST array. From there, you can do your checks and db call (or not), then add header("Content-Type:text/xml"); so the server sends it back with the correct header. After that you'll need to echo the XML-formatted data you want the JavaScript to receive. Just remember not to echo anything other than the XML if the request is supposed to go through.

how would I return any items in an array that do not match any $_POST results

I am writing a PHP/MySQL application that maintains a masterlist of user preferences and I've gotten myself stuck trying to remove items from that list. Currently the application generates a list of items and marks a checkbox next to the ones a user has previously selected, the user can then change their selections (either adding or removing checkmarks) and resubmit. The form only submits supplyid's for items the user has checked.
I have the list sorted so that unmarked selections are shown first and I've got the code to insert/update items in the database working, but I'm having problems figuring out how to delete the items the user has unchecked (and which now do not return supplyid's).
At this point, I've written a MySQL query to return only results that were previously included on the list (as those are the only ones which could need to be removed.) What I need are the items in the array returned by the query that do not match any $_POST results. I've been successfully comparing the array to the $_POST results of items previously included, but I can see my logic is wrong in the part where I'm trying to get back the results which don't match. While I'm able to view which items match, I'm not sure how to eliminate them as possibilities. Am I going about this in the wrong way entirely?
$iduser = $_SESSION["iduser"];
$possibleresults = $_POST["possibleresults"];
$sql_onlist = "select supply.idsupply from supply, kit
where supply.class = 'basic'
and kit.iduser = '".$iduser."'
and supply.idsupply = kit.idsupply";
$possible_delete = $connection->query($sql_onlist);
//for each record we know is already in the database, check to make sure it has been checked, otherwise delete
for ($i=0; $i<$possibleresults; $i++) {
$count = 0;
$item_delete = $possible_delete->fetch_assoc();
if ($_POST['item_'.$i.'']) {
$idsupply = $connection->real_escape_string($_POST['item_'.$i.'']);
//if there is a match, increase the counter
if ($idsupply == $item_delete["idsupply"]) {
$count++;
//this does successfully return a count = 1 - idsupply = number for all rows which should have matches
echo "count = ". $count . " - idsupply = " . $idsupply;
}
//this statement doesn't work because it doesn't know which idsupply
if ($count < 1) {
$idsupply = $item_delete["idsupply"];
$sql_delete = "delete from kit
where idsupply = '".$idsupply."'
and iduser = '".$iduser."'";
$result_delete = $connection->query($sql_delete);
}
}
There are a couple different solutions to this problem; here's a few strategies I've used before.
-- Delete all the entries every time you update a user's preferences
Not terribly efficient, but it's easy to implement. Every time they save their preferences, first set all the values in the database to whatever the 'unchecked' value is. Then, save their preferences as normal.
-- Give unchecked boxes a value
If you put a hidden input element right before a checkbox and give it the same name as the checkbox, the hidden element will submit its value whenever the checkbox is not checked. E.g.,
<input type='hidden' name='box1' value='off' />
<input type='checkbox' name='box1' value='on' />
This will let you know which IDs to unset in the database.
There may be a more database-oriented solution as well, but I'd have to know more about your structure to suggest anything.
Holy moly, what a tangled mess... kinda painted yourself into a corner eh? No worries it happens to all of us. :)
So I think that once you have a truly working algorithm the code just kinda comes together around it. So lets analyze your problem:
Your main objective is to store a users settings.
You are using a form and checkboxes to both display the current settings and to allow the user to change their current settings. This is graceful enough.
Generate a list of the users POSTed settings (aka get the new settings from the POST array) and store those results in a dedicated data container like an array or a linked list.
Once you have a list of new settings, you need to use that list as a map to set/unset various fields within a database table.
Get a list of ALL of the users saved settings from the database storing that in a different data container
Do a case by case comparison, seeing if the variables match, record the results in yet another data container, or do an immediate write to the database.
Present the user with a human readable result of their operation.
NOTE: Incidentally, you probably already know this, but if you use isset($_POST['mychkbox1']) and it returns a positive value, then that checkbox was checked. If isset() returns false, the checkbox was not set, or does not exist. Like I said you probably already knew that, but I figured I toss it in there.
Good luck
h
I didn't quite understand your code, but I think you need something like this
$to_keep = array();
for ( $i=1 ; $i < 10 ; $i++ ) {
// Add ids of elements we want to save
$to_keep[] = $i;
}
if ($to_keep) {
mysql_query("DELETE FROM table WHERE id NOT IN (". implode(',', $to_delete) . ")");
}

PHP Script for Datepicker to select and display database from Mysql

After spending 3 days on internet and struggling with so many different forums , i have found a match and similar case of my problem here.
Friends, I am zero in PHP, but still i have managed to do something to fulfill my requirement.
I am stuck with one thing now..So i need help on....
I am using one html+php form to submit database into mysql.
I created a display of that table through php script on a webpage.
Now i want a datepicker option on that displayed page by which i should able to select the date range and display the data of that date range from my mysql table.
And then take a export of data displayed of selected date range in excel.
This displayed page is login protected, so i want after login the next thing comes in should show a sate selection option which should be fromdate to to date , and then records should displayed from the database and i can take export of those displayed results in excel file.
The code i am using on this page is below which do not have any thing included for excel export and date picker script, I am pasting the code here and request you to please include the required code in it as required.
Thanks In advance
<?php
//database connections
$db_host = 'localhost';
$db_user = '***********';
$db_pwd = '*************';
$database = 'qserves1_uksurvey';
$table = 'forms';
$file = 'export';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table} ORDER BY date desc");
if (!$result) {
die("Query to show fields from table failed");
}
$num_rows = mysql_num_rows($result);
$fields_num = mysql_num_fields($result);
echo "$num_rows";
echo "<h1></h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>
This isn't a "write my code for me, please" site, so you're going to need to be a little more engaging and pro-acive. But we can certainly provide some guidance. Let's see...
Currently you have a page which displays all records from a given table, is that correct? And you need to do two things:
Before displaying any records, have the user select a date range. And keep the date range selection on the page so the user can re-select.
Provide a button which lets the user export the selected records to Excel.
For either of these, you're going to need to add an actual form to the page. Currently there isn't one. For the date picker, I recommend (naturally) using the jQuery UI datepicker. So the form for that would look something like this:
<form method="POST" action="myPHPFile.php">
<input type="text" id="fromDate" name="fromDate" />
<input type="text" id="toDate" name="toDate" />
<input type="submit" name="filterDate" value="Submit" />
</form>
<script>
$(function() {
$("#fromDate").datepicker();
$("#toDate").datepicker();
});
</script>
You may have to wrap the JavaScript in a $(document).ready(){} in order to make it work correctly, you'll want to test that. Anyway, this will give you a form to submit the dates to your script. Wrap the parts of your script which output data in a conditional which determines if the form values are present or not. If they're not, don't fetch any records. If they are, do some basic input checking (make sure the values are valid values, make sure fromDate is before toDate, etc.) and construct your SQL query to filter by date range. (Do take care to avoid SQL injection vulnerabilities here.)
For the Excel output, you may be able to find a ready-made solution for you that just needs a little tinkering. If I were to create one from scratch, I'd probably just output to a .csv file rather than a full Excel file. Most users don't know/care the difference. In that case, you'd just want to either create a second script which is nearly identical to the existing one or add a flag to the existing one which switches between HTML and CSV output, such as via a hidden form field.
For the output of the CSV, first make sure you set your response headers. You'll want to write a header to tell the browser that you're outputting a CSV file rather than text/html, and possibly suggest a file name for the browser to save. Then, the form inputs the SQL query will all be pretty much the same as before. The only difference is in the "HTML" that's being output. Rather than HTML tags, you'd wrap the records in commas, double-quotes (where appropriate), and carriage returns.
There's really nothing special to outputting a "file" vs. "HTML" because the HTTP protocol has no distinction between the two. It's always just text with headers.
Now, I'm sure you have more questions regarding this. And that's fine. In fact, we like to encourage asking (and, of course, answering) questions here. So please feel free to ask for clarification either in comments on this answer (or other answers), or by editing and refining your original question, or by asking an entirely new question if you have a specific topic on which you need help. Ideally, a good question on Stack Overflow consists of sample code which you are trying to write, an explanation of what the code is supposed to be doing, a description of the actual resulting output of the code, and any helpful information relevant to the code. As it stands right now, your question provides code somewhat unrelated to what you're asking, and you're just requesting that we add some features to it outright for you.

Categories