How to fill in placeholder boxes with a foreach loop? - php

Using PHP (at if it's need, jquery):
I have this page with 30 boxes. It will never be more, or less.
On those 30 boxes, some of them will be filled with "box specific" data.
How can I say:
If there are 20 records on the foreach to loop trought, then, 20 boxes will contain data, and the rest will stay with the placeholders.
If there are 10 records on the foreach, then 20 boxes will stay with the placeholdes.
How can something like this be achieved ?
Can anyone provide me a good example for doing so?
Thanks a lot,
MEM

Assuming $data is a numerically keyed array of your data:
<?php for($i = 0; $i < 30; $i++): ?>
<?php if(isset($data[$i]): ?>
<!-- the html for a box WITH data -->
<?php else: ?>
<!-- html for an empty placeholder box -->
<?php endif; ?>
<?php endfor;?>

Fill an array with the bits of data you do have, add 30 placeholders, take the first 30 elements of the array, and iterate over those.

Do you have names for each box? Assuming there is some name/id in your 10 or 20 records which I'm assuming are in an array...
function OutputBoxes($records, $boxes){
foreach($boxes as $box){
$box->PopulateWithPlaceHolder();
}
foreach($records as $record){
$box = GetMatchingBox($record);
$box->SetValue($record['valueProperty']);
}
foreach($boxes as $box){
echo $box->ElementHtml();
}
}
Assuming here that you have some type of box object which knows how to output itself as HTML, and set whatever value you would like that is coming from the record.

make an array with all your data. then run a for-loop (0..30) to build your boxes. For each item in your loop, if your box-data array contains an element, then output specific data, otherwise output placeholder data. Something like this...
<?php
$box_data = array(
"data for box 1",
"data for box 2",
"data for box 3"
);
for( $i=0; $i<30; ++$i ) {
if( $i >= count($box_data) ) {
// output "placeholder box"
echo "<div class=\"box placeholder\">Placeholder Box</div>";
} else {
// output the box's specific data
echo "<div class=\"box non-placeholder\">{$box_data[$i]}</div>";
}
}

Related

Entering three elements at different points in retrieval/list

I am listing batsmen and i have a page showing a top 50. What i want to do is have three separate points in the list where i can enter three different elements.
I would like to do this after the 10th, 24th, 42nd batsmen. How would i go about doing this with php?
My current code retrieves the batsmen and in my controller it has a take of 50
#foreach($batsmen as $bat)
<h2> $bat->name</h2>
<h3> $bat->nationality</h3>
<h3> $bat->highscore</h3>
#endforeach
In normal PHP you would use an index, and increment the index in your loop. I'm not clear with what your three different elements are, but this should help:
<?php
// Here $i is your index
$i = 1;
foreach($batsmen as $bat){
// When the index reaches 10, 24, and 42 then add the three different elements
// Anything output here is done every iteration of the loop
// and before your ads
if( $i == 10 ){
echo '<div id="ad1"></div>';
}
if( $i == 24 ){
echo '<div id="ad2"></div>';
}
if( $i == 42 ){
echo '<div id="ad3"></div>';
}
// Here we are incrementing the index
$i++;
// Anything output here is done every iteration of the loop
// and after your ads
}

Dealing with starting index in array - PHP

I've got an array of users from a database (I'm working in PHP, using CodeIgniter in Sublime)
I've got a view, that has a select that show display all the users, so in my view, at the top, I have this code (suppose that the arrays has 3 items):
<?php
$optionsUsers = array();
$qtyUsers = count($users); -->
if($qtyUsers > 0){
$optionsUsers[0]['name'] = 'Choose an option';
for($i=0; $i < $qtyUsers; $i++){
$optionsUsers[$i]['id'] = $users[$i]["userId"];
$optionsUsers[$i]['name'] = $users[$i]["username"];
}
}
?>
Then, in the select part, I have this:
<select id="cursadaUsuario">
<?php
$qtyOptionsUsers = count($optionsUsers);
if($qtyOptionsUsers>0){
for($i=0; $i<$qtyOptionsUsers; $i++){
if($i == 0){
echo '<option value="0" disabled selected>Please select an option</option>';
}else{
echo '<option value="'.$optionsUsers[$i]['id'].'">'.$optionsUsers[$i]['name'].'</option>';
}
}
}else{
echo '<option value="">There are no options available</option>';
}
?>
</select>
I've assigned to the $optionsUsers array in [0] the string "Choose an option" because when iterating THAT ARRAY in the select, I wanted to display it as disabled and just iterate the rest of the elements as usual
The problem is that array $users starts in 0 --> I've checked it with a foreach and all the users display are actually there:
foreach ($users as $key => $value){
print_r($users);
});
But I wanted [0] to be the text to display, "Choose your option", so if I assign the text to [0], the first item in array $users is never shown :( (in this example, it would iterate the text and 2 of the items, not the 3)
If I remove the text to [O], and just iterate the array, all the users are shown correctly, no one is missing, but that means... no text to tell "Choose an option" :/
I would like it to look like this --> http://www.hkvstore.com/phpreportmaker/doc/images/dropdownselect.png, so I want the text "Choose you option" to be shown AND disabled, and then the elements of the array, in my case, a list of users.
Note: I would like to keep using a 'for' loop.
Note2: This (Add option selected disabled in PHP) would be kind of similar to what I want to achieve, but still, I don't think I could just change the keys and assign my own to a list of users, the could be changed, added, deleted, etc.. :/
Ideas? Thanks in advance! :)
Unless I'm not understanding you, it's the same as the "No options available" option – it belongs outside the loop:
if ($qtyOptionsUsers > 0) {
echo '<option value="0" disabled selected>Please select an option</option>';
for ($i = 0; $i < $qtyOptionsUsers; $i++) {
echo '<option value="'.$optionsUsers[$i]['id'].'">'.$optionsUsers[$i]['name'].'</option>';
}
} else {
echo '<option value="">There are no options available</option>';
}
you need to push the users data from index 1 rather than from 0 index.Try below code to fix the choose option
for($i=0; $i <= $qtyUsers; $i++){
$optionsUsers[$i+1]['id'] = $users[$i]["userId"];
$optionsUsers[$i+1]['name'] = $users[$i]["username"];
}

Changing input format and database issue

I'm tasked with fixing a job information page at work. When someone clicks "edit job" to edit a job, a form of all the database titles and values is listed and they can click on an input box and change it and update. Basic stuff.
Now, in the input box for "Payment terms:" the percentages are written exactly like this, "40/40/20" and so in the database under payment they're listed as 40/40/20.
So the label + input box looks like this, Payment terms: [40/40/20].
<p><label for='payment'>Payment Terms</label><input name='payment'
id='payment' value='<?php if(isset($data2['payment'])) echo
$data2['payment']; ?>' /></p>
I want to change this to 4 drop down boxes where they can pick the percentages, for instance
Payment terms: [40]
[40]
[20]
[empty]
There is a TON of jobs with their own payment terms in the db and I think I may have to add 4 columns to the db instead of just 1 column named payment and values listed as %/%/%/%.
Obviously that doesn't seem like a good solution as it would take forever to fix all the jobs and enter their data for each term into the new columns.
What should I do ?
You can use explode to split the string from your database. Then you can make 4 <select> boxes:
<?php
$selects = 4;
if (isset($data2['payment'])) {
$percentages = explode("/", $data2['payment']);
// Make sure that the array is long enough by adding zeroes to the end
while (count($percentages) < $selects) $percentages[] = 0;
}
else {
$percentages = array_fill(0, $selects, 0);
}
$options = range(10, 100, 10);
for ($i = 0; $i < $selects; ++$i) { ?>
<select>
<option></option>
<?php foreach ($options as $o) { ?>
<option value="<?php echo $i; ?>"
<?php if ($o == $percentages[$i]) echo ' selected="selected"'; ?>>
<?php echo $o; ?>
</option>
<?php } ?>
</select>
<?php } ?>
I put the blank option first as it will be selected by default that way.

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

Unset item from Array $_FILES upload

I have a script where users can upload multiple files (max. 8). The HTML is generated by a piece of PHP:
$max_no_img=8;
for($i=1; $i<=$max_no_img; $i++){
<div class='photo photo$i'>
<div class='new_label'>
Foto $i:
</div>
<div class='new_input'>
<input type='file' name='images[]' />
</div>
</div>";
}
So the array images[] consists of 8 values. However, every time a user submit it's form, the form is generating an Array of 8 items and by so, inserting 8 values in the database (whether they are empty or not).
So I would like to unset the empty values, copy the files to my folders and insert the link into my database. But here is the part where the errors happen.
The array of $_FILES consists of 4 things. name, tmp_name, error and size. How do I get it so a complete item (let's say images[0]) will be unset from the array so I can continue with the items which actually carry a value.
I tried this, but with no results...
unset($_FILES['images'][0])
and
unset($_FILES['images']['name'][0])
unset($_FILES['images']['tmp_name'][0])
unset($_FILES['images']['error'][0])
unset($_FILES['images']['size'][0])
Any advice how to unset a value from a $_FILES-arry?
You can just ignore them instead of processing or unsetting any items:
if (!empty($_FILES['images'])) {
for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
if (empty($_FILES['images']['name'][$i])) {
// This item is empty
echo "Item $i references an empty field.\n";
continue;
}
echo "Item $i is a valid file.\n";
}
}
You do not actually need to unset any items. Simply skip over the items that don't correspond to an uploaded file:
for($i=1; $i <= $max_no_img; $i++) {
if(empty($_FILES['images']['name'][$i])) {
continue; // that's all it takes
}
}

Categories