Inserting words between strings - php

I am working on a PHP form that involves a multiselect checkbox. I want to load the options that were selected by the user into a string and echo it. I want to separate the options with commas and the word "and".
For example:
If a user selects just Option 1, I want to echo "opt1".
If a user selects Option 1 and Option 2, I want to echo "opt1 and opt2"
If a user selects Option 1, Option 2, and Option 3, I want to echo "opt1, opt2, and opt3".
Here is my HTML:
<p><b>Product:</b><br>
<INPUT NAME="product[]" TYPE="CHECKBOX" VALUE="opt1">
Option 1<BR>
<INPUT NAME="product[]" TYPE="CHECKBOX" VALUE="opt2">
Option 2<BR>
<INPUT NAME="product[]" TYPE="CHECKBOX" VALUE="opt3">
Option 3<BR>
<INPUT NAME="product[]" TYPE="CHECKBOX" VALUE="opt4">
Option 4<BR></p>
Thanks for helping a PHP noob!

If you want these opt values to dynamically load during run-time, you will need to use Javascript. PHP loads on the server-side when the page is initially loaded so when a user checks a box, PHP cannot do anything by itself to echo values to the screen again.

An easy solution would be to do three cases; one if there is only one selection, one for two selections, and one for more-than-2 selections.
This (untested) solution should get you in the right direction:
<?php
$products = (isset($_POST['product']) && is_array($_POST['product'])) ? $_POST['product'] : array();
$count = count($products);
$options = '';
if ($count == 1) {
$options = $products[0];
} else if ($count == 2) {
$options = $products[0] . ' and ' . $products[1];
} else if ($count > 0) {
// remove (and store) the last product selected
$last = array_pop($products);
// join all remaining products by comma-separation, then add the last product
// to the end with an "and"
$options = implode(', ', $products) . ' and ' . $last;
}
echo $options;
?>
Please note, the above solution also assumes you're receiving the user-selection via a POST array.

Firstly, correct grammar states that you don't put a comma before the final and.
So, what you really need to do is separate the last two words with and, and the others with ,.
Well, assuming you have your words in an array already, all you have to do is array_pop the last element off the end. Then join the remaining elements with ,, and put it together with the last one with and in between. If there is only one word, just return it.
We're not here to write code for you, but this shoud help you along.

Related

What is the best way to write the code that sum the values of checkbox choices

I would like to have a form that enables a user to choose the vehicles. The user should get the total price of his choice. I wrote this little script, and it works properly. I am just curious is there a better way to do it. For example, there are a lot of IFs in foreach loop. What if I have, for instance, 100 checkboxes. Should I automate that in a way that for every new type of vehicle the script should make new IF statement? That sounds awkward. Is there a way to put a number of prices directly in checkbox form or something? However, what would be the best way to do such a thing. Thanx.
if (isset($_POST['submit'])){
$automobils=$_POST['auto'];
$set= array();
echo "You ordered: " ;
foreach ($automobils as $model){
if ($model == "chevrolet"){
$set[]=20000;
}
if ($model == "reno"){
$set[]=15000;
}
if ($model == "punto"){
$set[]=10000;
}
echo "<i>$model </i>";
}
$sum = array_sum($set);
echo "</br> Whole price is $sum $";
}
?>
<form action="" method="post">
<input type="checkbox" name="auto[]" value="chevrolet"/> Chevrolet</br>
<input type="checkbox" name="auto[]" value="reno"/> Reno</br>
<input type="checkbox" name="auto[]" value="punto"/> Punto</br>
<input type="submit" name="submit" value="Submit"/>
</form>
Well without adding a database and a whole another level of fun programming.
You can do this with an explode command (And really shrinks your foreach as well)
on the input value
value="chevrolet"
Change to something like
value="chevrolet;20000"
then in your foreach loop
foreach ($automobils as $model){
$eachmodel = explode(";",$model);
$set[] = $eachmodel[1];
}
Ideally you'd store your possible values, and their corresponding prices, in a database, rather than in your code. But here's a quick solution, involving an associative array acting as a map between each vehicle and its price.
$map = [
'chevrolet' => 20000,
'reno' => 15000,
'punto' => 10000
];
if (!empty($_POST['auto']) {
echo 'You ordered:<br />';
$total = 0;
foreach($_POST['auto'] as $model)
if (array_key_exists($model, $map)) {
echo ' - '.$model.'<br />';
$total += $map[$model];
}
echo 'Total price: '.$total.'<br />';
}
Then, you just update the map as you add/change vehicles/prices etc.
Note it's key to store the allowed values/prices code-side (or in a DB) rather than in your form as the latter is editable via the DOM, so you'd need something server-side to validate it anyway.
If you want to put number in checkbox. You can put it with value by using some special separator.
For example
<input type="checkbox" name="auto[]" value="punto_20000"/> Punto</br>
Later you can use Explode string and can get value for selected.

How to have checkbox items create a list

I am new to PHP and the project I am working on is a codeigniter php form writing back to a FileMaker database.
The checkboxes should be populating as a list field.
Here is my form
<input name="fieldname[]" value="value1"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value1
<input name="fieldname[]" value="value2"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value2
There are about 7 checkboxes.
I assume that I have to setup a foreach loop to get it to go thought to FileMaker's field, but unsure how to do that.
If I take away the array, the last one selected goes through to the layout.
Any help would be great.
Presumably, these values mirror a valueList back in FileMaker. If so, it's best to assign the valueList to a variable:
$values = $layout->getValueList('pizzaToppings');
And use that in your for loop:
foreach($values as $value)...
In your if(isset()) block, post a return-delimited array to FileMaker:
// value(s)!
if ($_POST['fieldname']) {
$valueArray = implode("\r", $_POST['fieldname']);
}
// pass the array to setField()
$record->setField('filemakerField', $valueArray);
I worked it out. To enter checked boxes into a return separated list:
View:
At the top of the section with the checkboxes
<?php $join->fieldname = explode("\n", $join->fieldname); ?>
// The actual input in the form
<input name="fieldnameXX[checkboxValue]" value="value" <?php echo (in_array('value', set_value('fieldname[value]', $join->fieldname)) ? ' checked="checked"': '')?> type="checkbox" class="form-check-input" > Value
Factory:
$fieldnameZZ = $data['fieldnameXX'];
$data['fieldnameXX'] = FALSE;
unset($data['fieldnameXX']);
$sacraments = implode("\n", $fieldnameZZ);
$data['fieldname'] = $fieldnameZZ;
I'm not sure if this is the best way to have done it, but it works.
$ids=implode(",", $_REQUEST["fieldname"]);
$result3=mysqli_query($dbh,'SELECT* FROM excel_tenant WHERE ID IN ("' .
$ids . '") AND
ManagerID = "'.$_SESSION["ManagerID"].'" ORDER BY ID DESC ') or
die(mysqli_error($dbh));

counting number of checkboxes check in email

Here is my php code:
$tasks = ' ';
$help = $_POST['help'];
if(empty($help))
{
$tasks = "None selected.";
}
else
{
$N = count($help);
$tasks = $N;
}
And the HTML is:
<input type="checkbox" name="help" value="sign"> //with several inputs with different values
On the form submit, it emails and outputs everything appropriately except the count of the array. It outputs the $tasks variable at the end of the email always as 1, except when no check boxes are selected. Any combination of selecting checkboxes (1-6) ends up with an array of 1 length. Anyone know why? Thanks!
You'll need to make the checkboxes an array. Change the name to:
<input type="checkbox" name="help[]" value="sign">
You should change your HTML code to:
<input type="checkbox" name="help[]" value="sign">
so that help will be an array. If you only use help, $_POST['help'] will only contain the last value.
you have to rename fields name="help[]" so it can be parsed as array.

checkbox's stay checked after pagination in php

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'>";

How to delete many records at a stretch?

In Php as we all know, there are no inbuilt controls by itself like Asp.Net's GridView etc. I am using Html's <table> to build up the grid and keep the row's id in one hidden field. I've also placed one checkbox at the beginning of each row and a delete button at the bottom of the grid. The problem i face is, how do i get all the id's that are checked so that i can pass those ids in my IN clause of Delete?
Take a look at what is currently being submitted:
var_dump($_POST);
You will see all of the field values. If you do the checkboxes right, you'll have an array of rowID's to delete, and you can simply implode(',',$_POST['checkBoxes']) or something similar when building your query.
Security would be a concern here... I'm sure someone else will post in depth about that, but you definitely want to validate that the user can delete these records.
Name every checkbox with a semi-unique name like tablerow[numeric_id]. When you submit the form you can simply catch all posted tablerow value that was checked.
First you name all your checkboxes by suffixing [] in their name so that an array gets created, later this is how you can get those that are checked and act accordingly:
for($i = 0; $i < count($_POST['checks']); $i++)
{
if (isset($_POST['checks'][$i]))
{
// this was checked !!
}
}
Where checks is the name of all those checkboxes eg:
<input type="checkbox" name="checks[]" value="1" />
<input type="checkbox" name="checks[]" value="2" />
<input type="checkbox" name="checks[]" value="3" />
And this is how you can get those for your IN clause in your query:
$checked_array = array();
for($i = 0; $i < count($_POST['checks']); $i++)
{
if (isset($_POST['checks'][$i]))
{
$checked_array[] = mysql_real_escape_string($_POST['checks'][$i]);
}
}
// build comma separated string out of the array
$values = implode(',', $checked_array);
Now you can use the $values in your IN clause of your query.

Categories