Entering three elements at different points in retrieval/list - php

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
}

Related

how to get Multiple values in views page

Actually, cities are stored multiple values(with ids)
Example
(3,5)chennai,bangalore in one table.
How to get city names with the separated comma in views page.
controller code
$data['jobCityName'] =explode(',',$viewData['jobCity']);
for($i= 0; $i < sizeof($data['jobCityName']); $i++) {
$jobMultipleCity= $data['jobCityName'][$i];
$data['jobCityNames']=$this->hrm_model->getCitybyId($jobMultipleCity);
$data['jobCity']=$data['jobCityNames']['cityName'];
views Page Code
<?php echo $jobcity; ?>
present printed only one city name.
how to display cities in views page like(hyderabad,chennai,bangalore)
You can use foreach for iteration. Also you are overwriting previous value at $data['jobCity']=$data['jobCityNames']['cityName'];
like
$data['jobCityName'] =explode(',',$viewData['jobCity']);
foreach($data['jobCityName'] as $cityid) {
$data['jobCityNames']=$this->hrm_model->getCitybyId($cityid);
$data['jobCity'].=$data['jobCityNames']['cityName'];
}
Also it's recommended to use count instead of sizeof

Display loop data in sorted manner

I want to display <li> where, I am having issue with my loop, see my code below
<?php
for ($j=0;$j<$task_count;$j++)
{
$task_name = $task[$j]['summary'];
$summary_length = strlen('');
$task_id = $task[$j]['_id'];
$task_status = $task[$j]['status'];
$summary_count = strlen($task_name);
if ($task_name=='task') {
$final_task_summary = $task_id ;
}
elseif($summary_count <= 50)
{
$final_task_summary = $task_name;
}
else
{
$final_task_summary = mb_substr($task_name, 0, 50);
}
?>
Here, I want to display <li> </li> in order where first it shows <li> having status "open" then "resolved" and then "close" and only 20 <li> should take place.
If I understand correctly, you want to:
Print list items for the first 20 items.
Printing should be done ordered based on status.
If you're getting the data from a database, then it would be better to handle this in the query, If not, you can do as follows.
Change your loop to get only 20 items instead of task count
Declare three strings to hold li items for each status.
Within the loop, Check for the status and append the desired string with li items.
After the loop, print the three strings in the required order.
Let me know if anything needs clarification.
Thanks,

PHP conditional processing required to display rotating banners continuously

I'm trying to do something a little different with a banner rotator.
Below is the script I am using to read two text files (stored on my root directory with .db extensions) to rotate banners on a website. One file holds a counter (FileDB), the other holds the HTML banner code (URLDB).
The URLDB file currently holds six lines of HTML code to display hyperlinked banners.
The following script builds an array and rotates these banners sequentially on the refresh of the page counting from 0 - 5, and it does this perfectly:
<?php
define('FILEDB', '/WORKING DIRECTORY/count.db');
define('URLDB', '/WORKING DIRECTORY/url.db');
function readURLS()
{
$fo = fopen(URLDB, 'r');
if( null == $fo )
return false;
$retval = array();
while (($line = fgets($fo)) !== false)
{
$retval[] = $line;
}
return $retval;
}
$list = readURLS();
if( false === $list )
{
echo "No URLs available";
}
else
{
$fo = fopen(FILEDB, 'a+');
$count = (fread($fo, filesize(FILEDB)) + 1) % count($list);
ftruncate($fo, 0);
fwrite($fo, "{$count}");
fclose($fo);
echo $list[$count];
}
?>
On the webpage that I want to display the banners there are eight placeholders. However I only have six banners.
Here is the PHP code in each of the placeholders:
Placeholder 1: <?php echo $list[$count];?>
Placeholder 2: <?php echo $list[$count +1];?>
Placeholder 3: <?php echo $list[$count +2];?>
Placeholder 4: <?php echo $list[$count +3];?>
Placeholder 5: <?php echo $list[$count +4];?>
Placeholder 6: <?php echo $list[$count +5];?>
Placeholder 7: <?php echo $list[$count +6];?>
Placeholder 8: <?php echo $list[$count +7];?>
With the count at 0 the 6 banners are displayed in placeholders 1 - 6 and placeholders 7 and 8 are blank.
With every refresh the counter is increase by one, showing each banner in the first placed holder and pulling the other banners through each placeholder from 5 through to 0, but leaving previously populated placeholders blank until the sixth banner is in placeholder one. Then on the next refresh banners 1 - 6 are once again shown.
This occurs because I've hardcoded the values in each placeholder and I am obviously attempting to reference an entry in the file that is out of the bounds of the array built by the above script.
You can see a working example here.
What I am trying to achieve is display all banners in the URLDB such that when the last entry is shown, the first entry is displayed in the next placeholder (which in this case is placeholder 7) and the 2nd entry is show in in placeholder 8.
The idea is that the banners move continuously through each of the placeholders like the carriages of a train with each page refresh and increment of the counter - one following the other.
So, now you have the background, on to my question.
Is there a way I can amend the script to store in a PHP variable the maximum number of entries in the URLDB file/array and subsequently add conditional processing in the placeholders to check when the counter reaches this maximum value, and reference the next valid value in the array (i.e. 0) such that the banners restart again in the surplus placeholders - so here are no blank or empty placeholders shown?
I imagine this might seem like a strange request. But of course I would appreciate any advice on how to achieve my goal based on where things are currently.
Once you use a loop things become a bit easier to manipulate.
Hopefully the following solves your problem.
$numOfBanners = count($list);
$numOfPlacements = 8;
for ($i=0; $i < $numOfPlacements; $i++) {
// use the modulus operator to come back around
$bannerID = $i % $numOfBanners;
echo $list[$bannerID];
}
More info on the modulus operator can be found here.

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 fill in placeholder boxes with a foreach loop?

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

Categories