I have a PHP page with a list of items pulled from a database. Each item has an input form next to it, and right at the bottom, a submit button.
How can i do a POST check to find out which inputs have had data added? I can get the data, but how do I know the names of the particular inputs that have been filled?
Iterate over $_POST and list the keys which have nonempty values.
foreach ($_POST as $key => $value) {
if (!empty($value)) {
echo $key . " was filled in.";
}
}
Take a look at the isset() function of PHP - http://php.net/manual/en/function.isset.php.
For Example,
<?php
if(isset($_POST['somevar'])) {
// if the value has been set, this code is executed
} else {
//value not set, so execute this code.
}
?>
Related
Re-writing the question here so it's (hopefully) easier to understand.
I have a piece php that received a $_POST from a form. Each time a $_POST is completed, only one set of data is sent. It could be $_$POST['boat'] or $_POST['car'] or $_POST['dog'] etc. I do not know what the post will contain upon receiving it. If it is $_POST['dog'] then the value of the post will go into the $database.dog table. If it is $_POST['car'] then the value of the post will head into the $database.car table, and so on.
Once a post is made, how can I identify whether the post was called 'car' or 'dog' or 'boat' or anything else ?
There's a lot of ways to do this. Simply with ifs:
if(isset($_POST['car'])) {
// do car stuff
}
if(isset($_POST['boat'])) {
// do boat stuff
}
//etc...
Or a switch:
switch(true) {
case(isset($_POST['car'])):
// do car stuff
break;
case(isset($_POST['boat'])):
// do boat stuff
break;
//etc...
}
To avoid the ifs or switch you can use a hidden input:
<input type="hidden" name="form" value="car">
Then use $_POST['form'] to dynamically build your queries etc...
If car or boat etc... is the only key under $_POST or if it is always the first key then:
$form = key($_POST);
You can get the key/index and value and print that info if you are unsure what the keys or values will be that are coming from your form POST.
function getKeyValuePairs() {
$stmt = null;
if(isset($_POST)){
foreach($_POST as $key => $value) {
$stmt .= $key." => ".$value."<br>";
}
print_r($stmt);
}
Because $_POST is global no need to push variable into function.
HTML: run function to print key/value pairs
<div>
<?php echo getKeyValuePairs(); ?>
</div>
if($_POST)
{
if(array_key_exists("item_id", $_POST)) // asking if the array exists in data.php,
{
$item_ids = $_POST["item_id"]; // temp var. to hold the data.php data
$price=0;
foreach ($items as $item)
{
foreach($item_ids as $value)
{
if($value==$item['id']) //checking for the ids that were store in array
$price+=$item['price']; // adds price of the ids that are selected
}
}
require_once("view_confirm.php"); //shows the total of price in the view_confirm.php
die();
//if there wasnt any selected boxes its set to true for a statement to be stated on view_items
}
$error_no_items_selected =true;
}
My function works, I have a problem displaying an error message when the there is no click boxes, I set the value to false above post, $error_items_selected, on my view_items.php is HTML code, where I also use:
<?php if(error_items_selected==true){echo "Click Something";}
every time I refresh the page the message already appears,
In
if(error_items_selected==true){echo "Click Something";}
error_items_selected should have a $ if it's a variable.
Or () if it's a function call.
If you use error_items_selected - PHP considers it a constant. And if you don't have such constant, that is obvious, error_items_selected is considered a 'error_items_selected' string which is definitely true.
So proper way should be:
if ($error_items_selected==true){echo "Click Something";}
Also in first code block you use $error_no_items_selected. Maybe it's just different variables, but still - check them.
ok i have dynamically created form elements with unique names and when validated i want to store all the form data into SESSION.
This is the code to do it:
if(isset($_POST["address_submit"])){
insertSessionVars();
header("Location: http://localhost/project%20gallery/notes.php");
exit;
}
function insertSessionVars(){
foreach($_POST as $fieldname => $fieldvalue){
$_SESSION['formAddresses'][$fieldname] = $fieldvalue;
}
}
This works almost fine but stores also submit button value. I output it like this:
foreach($_SESSION['formAddresses'] as $value){
echo $value;
}
Any help will be greatful :)
Don't assign a name attribute to your submit button. If you assign a name then it is passed as part of the $_POST array.
<input type="submit" value="My Button" />
Since you no longer have the submit button in post, instead of checking if the submit button is set check to see if the post array contains data using count().
if(count($_POST) > 0)
The $_POST values are just array so after the for each why don't you use unset to drop the submit key from the array
That way you can check the form has been submitted and the either choose to not set the submit key or drop it rather then not giving it a name at all
Either way you can in your foreach do something like this (see *) and pass "$except" as parameter.
Where $except has to be the name of your submit button in insertSessionVars();
if(!in_array($key, $except)){...}
And ofc above your foreach something like this :
if(!is_array($except)) $except=array($except);
I am trying to process a form which I don't know ahead of time what the form fields will be. Can this still be done in PHP?
For example I have this html form:
<form method="post" action="process.php">
<?php get_dynamic_fields(); // this gets all the fields from DB which I don't know ahead of time what they are. ?>
<input type="submit" name="submit" value="submit" />
</form>
And here is what I have in the PHP process file
<?php
if ( isset( $_POST['submit'] ) && $_POST['submit'] === 'submit' ) {
// process form here but how do I know what field names and such if they are dynamic.
}
?>
Here is a caveat: assuming I can't get the data from the db ahead of time, is there still a way to do this?
Sure, just iterate over all the items in the $_POST array:
foreach ($_POST as $key => $value) {
// Do something with $key and $value
}
Note, your submit button will exist in the array $_POST, so you may want to write some code to handle that.
You can iterate over all $_POST keys like this.
foreach($_POST as $key => $value)
{
echo $key.": ".$value;
}
This will give you the field names used in HTML form.
$field_names = array_keys($_POST);
You can also just iterate through the POST array using
foreach($_POST as $field_name => $field_value) {
// do what ever you need to do
/* with the field name and field value */
}
you could loop over all parts of the `$_POST array;
foreach($_POST as $key => $value){
//$key contains the name of the field
}
Get the names of the fields from your get_dynamic_fields function and pass them in a hidden input that is always an array with a static name. Then parse it to get the names of the inputs and how many there are.
Hello i want any checkbox i am gonna check, to stay checked after pagination.
here is the code:
foreach($test as $string){
$queryForArray = "SELECT p_fname,p_id FROM personnel WHERE p_id = " .$string["p_id"]. " ;" ;
$resultForArray = mysql_query($queryForArray, $con);
$rowfForArray = mysql_fetch_array($resultForArray);
?>
<td id="<?php echo $rowfForArray["p_id"]?>" onclick="setStyles(this.id)" ><?php echo $rowfForArray["p_fname"]?></td>
<td><input id="<?php echo $rowfForArray["p_id"]?>" class="remember_cb" type="checkbox" name="how_hear[]" value="<?php echo $rowfForArray["p_fname"]?>"
<?php foreach($_POST['how_hear'] as $_SESSION){echo (( $rowfForArray["p_fname"] == $_SESSION) ? ('checked="checked"') : ('')); } ?>/></td>
</tr>
<tr>
I am geting the data from a search result i have in the same page , and then i have each result with a checkbox , so that i can check the "persons" i need for $_Session use.
The only think i want is the checkbox's to stay checked after pagination and before i submit the form!(if needed i can post the pagination code, but he is 100% correct)
In the checkbox tag use the ternary operation, without that foreach inside him:
<input [...] value="<?php echo $rowfForArray["p_fname"]?>" <?php $rowfForArray["valueToCompareIfTrue"] ? "checked='checked'" : ''; ?> />
because the input already is inside of 'for' loop, then each time of the loop will create a new checkbox wich will verify if need to being check or not.
I hope I have helped you.
A few ways to tackle this:
(Straight up PHP): Each page needs to be a seperate form then, and your "next" button/link needs to submit the form everytime they click next. The submit data should then get pushed to your $_SESSION var. The data can then be extracted and used to repopulate the form if they navigate backwards as well. Just takes some clever usage of setting the URL with the proper $_GET variables for the form.
(HTML5): This will rely more on JavaScript, but basically you get rid of pagination and then just break the entire data set into div chunks which you can hide/reveal with JavaScript+CSS or use a library like JQuery.
(AJAX): Add event listeners to the checkboxes so that when a button is checked an asynchronous call is made back to a PHP script and the $_SESSION variable is updated accordingly. Again, this one depends on how comfortable you are with JavaScript.
Just keep in mind that PHP = ServerSide & JavaScript = ClientSide. While you can hack some PHP together to handle "clientside" stuff, its usually ugly and convoluted...
I did it without touching the database...
The checkbox fields are a php collection "cbgroup[]".
I then made a hidden text box with all the values which equal the primary keys of the selectable items mirroring the checkboxes. This way, I can iterate through the fake checkboxes on the current page and uncheck the checkboxes by ID that exist on the current page only. If the user does a search of items and the table changes, the selectable items remain! (until they destroy the session)
I POST the pagination instead of GET.
After the user selects their items, the page is POSTED and I read in the hidden text field for all the checkbox IDs that exist on that current page. Because PhP only tells you which ones are checked from the actual checkboxes, I clear only the ones from the session array that exist on the POSTED page from this text box value. So, if the user selected items ID 2, 4, 5 previously, but the current page has IDs 7,19, and 22, only 7, 19, and 22 are cleared from the SESSION array.
I then repopulate the array with any previously checked items 7, 19, or 22 (if checked) and append it to the SESSION array along with 2, 4, and 5 (if checked)
After they page through all the items and made their final selection, I then post their final selections to the database. This way, they can venture off to other pages, perhaps even adding an item to the dB, return to the item selection page and all their selections are still intact! Without writing to the database in some temp table every page iteration!
First, go through all the checkboxes and clear the array of these values
This will only clear the checkboxes from the current page, not any previously checked items from any other page.
if (array_key_exists('currentids', $_POST)) {
$currentids = $_POST['currentids'];
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$removeItems = explode($delimiter, $currentids);
foreach ($removeItems as $key => $del_val) {
//echo "<br>del_val: ".$del_val." - key: ".$key."<br>";
// Rip through all possibilities of Item IDs from the current page
if(($key = array_search($del_val, $itemList)) !== false) {
unset($itemList[$key]);
//echo "<br>removed ".$del_val;
}
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
// Leaves the previous paged screen's selections intact
$newSessionItems = implode(",", $itemList);
$_SESSION['materials'] = $newSessionItems;
}
}
}
Now that we have the previous screens' checked values and have cleared the current checkboxes from the SESSION array, let's now write in what the user selected, because they could have UNselected something, or all.
Check which checkboxes were checked
if (array_key_exists('cbgroup', $_POST)) {
if(sizeof($_POST['cbgroup'])) {
$materials = $_POST['cbgroup'];
$N = count($materials);
for($i=0; $i < $N; $i++)
{
$sessionval = ",".$materials[$i];
$_SESSION['materials'] = $_SESSION['materials'].$sessionval;
}
} //end size of
} // key exists
Now we have all the items that could possibly be checked, but there may be duplicates because the user may have paged back and forth
This reads the entire collection of IDs and removes duplicates, if there are any.
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$filtered = array();
foreach ($itemList as $key => $value){
if(in_array($value, $filtered)){
continue;
}
array_push($filtered, $value);
}
$uniqueitemschecked = count($filtered);
$_SESSION['materials'] = null;
for($i=0; $i < $uniqueitemschecked; $i++) {
$_SESSION['materials'] = $_SESSION['materials'].",".$filtered[$i];
}
}
}
$_SESSION['materials'] is a collection of all the checkboxes that the user selected (on every paged screen) and contains the primary_key values from the database table. Now all you need to do is rip through the SESSION collection and read\write to the materials table (or whatever) and select/update by primary_key
Typical form...
<form name="materials_form" method="post" action="thispage.php">
Need this somewhere: tracks the current page, and so when you post, it goes to the right page back or forth
<input id="_page" name="page" value="<?php echo $page ?> ">
if ($page < $counter - 1)
$pagination.= " next »";
else
$pagination.= "<span class=\"disabled\"> next »</span>";
$pagination.= "</div>\n";
Read from your database and populate your table
When you build the form, use something like this to apply the "checked" value of it equals one in the SESSION array
echo "<input type='checkbox' name='cbgroup[]' value='$row[0]'";
if (isset($filtered)) {
$uniqueitemschecked = count($filtered);
for($i=0; $i < $uniqueitemschecked; $i++) {
if ($row[0] == $filtered[$i]) {
echo " checked ";
}
}
}
While you're building the HTML table in the WHILE loop... use this. It will append all the select IDs to a comma separated text value after the loop
...
$allcheckboxids = "";
while ($row = $result->fetch_row()) {
$allcheckboxids = $allcheckboxids.$row[0].",";
...
}
After the loop, write out the hidden text field
echo "<input type='hidden' name='currentids' value='$allcheckboxids'>";