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.
Related
im trying to write a loop that displays the counter on one line, been sitting here for over an hour but cant figure it out.
The main loop is
while($counter< 100){
echo $counter;
usleep($timeInSeconds*1000000);
$counter=$counter+1;
}
Now this prints 100 numbers after a delay each on a new line. Is it possible for the echo to instead replace itself for each loop?
I tried many options, here is one that didnt crash:
while($counter < 100){
$counter=$counter+1;
echo $counter;
usleep($timeInSeconds*1000000);
flush();
ob_flush();
}
However, with this option it works in one line with a delay, but it doesnt clear the previous echo, so its just a bunch of number next to each other
Could someone help me out?
You are trying to do something on the server that should be done on the client.
I expect you are making a timer. You should write some JavaScript code instructing the web browser on how to display multiple numbers with a delay in between. Your current code will show a loading wheel and a blank screen for the entire duration on many browsers.
Instead, replace your loop with something like:
var time_in_seconds = 1; // You can replace 1 with the value of the PHP variable
var count_element = document.getElementById("example_counter");
var n = 0;
var interval_id;
function update_counter(){
n += 1;
if (n >= 100) {
clearInterval(interval_id);
}
count_element.textContent = n;
}
interval_id = setInterval(update_counter, time_in_seconds * 1000);
<span id="example_counter"></span>
Is there any way to create a new a href that remembers all the submitted data earlier. I don't know how to say it properly so I will describe in the code:
The first button
Click me
After the user clicks it, he is redirected to the same page but with the new button :
Click me
And so on :
Click me
How do i create the n variable to be added and increased after the button is pressed ?
( I have a table displayed from a database by using the while command with mysqli_fetch_array($database); )
The table is created like (trivial ) :
$retrieve_items = mysql_query("SELECT * FROM items WHERE id > 0");
$col = 0;
echo '<table width=100% border= 1><tr>';
while($row = mysql_fetch_array( $retrieve_items )) {
$col ++;
echo '<td>'.$row['name_item'].'</td>';
if ($col % 5 == 0 )
{
echo '</tr><tr>';
}
}
echo '</tr></table>';
I recommend not to try managing numbered variable names. If there is no important reason to do so, it will make your logic unnecessarily complicated.
PHP understands array parameters in e.g. $_GET. They are passed from HTML with empty braces appended to the parameter name.
This is a little demo to illustrate this alternative approach:
<?php
// get the passed array or generate a new one
$n = isset($_GET['n']) ? (array) $_GET['n'] : [];
//ppend 2 random numbers
$n[] = rand(1,100);
$n[] = rand(1,100);
//output the link with GET parameters in query
?>
the link
<!-- or let PHP's built-in generate a propper query --><br>
the link
Be aware, that the second link generated by http_build_query contains indexes of the array, which are commonly based on 0.
in php, to access the current query String, you can use
$_SERVER['QUERY_STRING']
so you could so something like
Click me
or you could replace your previous value in the query string
I want the Code below to read individual line of text from dataFile.txt and show it in input field.
Problem is After reading first line from text document it shows all remaining lines of text from text file into input field. But on clicking submit it should show second line only then again on submitting it should show third line only, inside input field. please help.
<?php
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$array1 = array();
<form action="datagGet.php" method="get">
<input type="text" value="
<?php while ( $line = fgets($f, 100) )
{
$nl = mb_strtolower($line);
echo $nl;
if(isset($_GET['done']))
{
$nl++;
}
else
{
break;
}
}
?>"
name="someText">
<input type="submit" name="done" >
</form>
You have several problems with you code. And the first comment above points to many of the. Key is the fact that the $_GET['done'] is set for the form submit and therefore you will echo all the lines of the output. It never breaks.
Also there is the fact that you are opening the file for reading each submit of the form. Although I don't see a simple way around this unless you store the file contents between requests.
One possible option is to use 'file()' to read the entire contents into an array. And then use sessions to store which line has been read. Then on each submit, look for the index of the array from the session read; advance it by one read the file again and return that line. Wow wasteful. But okay for simple site.
so use file to get the lines in an array.
output the first line into the value.
store the next index to be read in the $_SESSION variable like $_SESSION['next_line'] = 1
then upon further submissions. read it all back in. look up the 'next_line', and output that line.
so, for example
$array = file('your file name');
$output = $array[0];
if (isset($_SESSION['next_line']))
$_SESSION['next_line'] = intval($_SESSION['next_line']) + 1;
else
$_SESSION['next_line'] = 1;//prime the pump
echo the form with $output
then rinse and repeat. e.g. read, get output (next_line) with file, set $_session = next_line + 1; render output in form.
ps. some extra notes
* of course you'll need to start session on each request.
* you'll need to check if the $_SESSION['next_line'] is set. if not, set it to 1 (prime it)
I have a li and inside that i have a div class="reload" that have some content that should be reloaded for every 10 sec.
<li class="b1">
<div class="reload">
</div>
</li><!--col-->
So therefore i have got a script that does just that.
<script type="text/javascript">
$('.b1').children('.reload').load('php/reload/reload.php'); // load the content at start
window.setInterval(function(e) {
$('.b1').children('.reload').load('php/reload/reload.php'); // reload the content every 10 sec
}, 10000);
In the reload.php i get some content from a database. It looks like this, sort of..
<?php
// login info
require("../../connection_to_database_login.php");
// My query
$result = mysqli_query($l,'SELECT * FROM abcd WHERE efg=1 LIMIT 1');
// include some stuff
$r = mysqli_fetch_row($result);for ($p = 0; $p < $r[4]; ++$p){include("../some/stuff_$p.php");};
// include a random picture script or just load a picture
if ($r[4] == 0){include ('getRandPic.php');}
else {echo ('<img src="images/picture.png" />');}
?>
So far so good.. everything works.
The getRandPic.php file.. select one random picture from a folder
<?php
$img_dir = "images/images";
$images = scandir($img_dir);
$html = array();
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) {
$html[] .= '<img class="img-responsive" src="'.$img_dir.$img.'" />';
}
else { continue; }
};
echo $html[rand(0,6)];
?>
So this works ok.
But the thing is, i want to check if it shall "include a random picture script or just load a picture" every 5sec.
Therefore i need to check "if ($r[4] == 0)" every 5 sec.
So my question is: Is there any other way to do that?
As you asked in the comment... This is a rough guide only. You will have to develop and write your own code based on this guide.
Step 1a: optional
Make an ajax call from your webpage to the server. to get image file names.
Step 1b:
On server side in php file perform DB operation.
Let assume you have a table imageTable and column name images so you would read from DB using query SELECT images FROM imageTable
You will have to change the query, add condition (e.g. all images with animal and cute tags) to it and if you want limit the number of files that you want to randomize then you will have to add that as well.
Step 2:
Once you read from DB, as you are already doing, read all image names and put it in json format (json_encode). I personally prefer json. If you prefer, you can also return all names in simple string where names are separated by comma.
Step 3:
Store your response in JS.
var imagesArray = new Array();
$.ajax({
type: 'post',
url: pathtophpfile,
success: function(htmll) {
// get object with all data
imagesArray= JSON.parse(htmll);
},
});
Step 4:
Once you have it in your js object named imagesArray, use setInetval to perform task every 5 seconds.
Read a random value from 0 to imagesArrays length, and change the source of your image tag, <img class="img-responsive" src="+ randomimage +" />
Periodic updater will do your task.
Use ajax framework, it will reduce your db connection burden at the server side.
Have a look at it. It is a simple and nice way to achieve your task.
http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/
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'>";