Disable PHP count? - php

So, I am trying to modify a piece of code that I have, it is a calendar that is used for taking reservations. I am posting events on the calendar that users will be able to book by clicking on the link on any given day. It currently allows me to only post 2 events for booking, on any given day. These 2 cannot be at the exact same time. I want to change that, I need it to be able to post multiple spots available at the exact same time. For example, if it is a martial arts class and there are 10 open spots, it should show 10 spots available at the same time of day... You get the point...
I believe this is what is preventing me from achieving that, but im not certain...
Any help is much appreciated. Thanks is advance.
<script>
<?php
if($numslots>0) {
?>
alert('<?php echo $numslots; ?> slots added');
<?php
} else if($numslots == -1) {
?>
alert('Days selected are holidays. Cannot make these changes');
<?php
} else {
?>
alert('Duplicate slots. Cannot make these changes');
<?php
}
?>
document.location.href="calendar_manage.php?calendar_id=<?php echo $_GET["calendar_id"]; ?>&ref=slots";
</script>

In your example, where you have ten slots available for one time, you need to populate a new variable.. lets call it $available_slots.. you need to populate this with the number of slots, in this case ten. So you would end up with ...
$available_slots = 10;
if($numslots<$available_slots) {
?>
alert('<?php echo $numslots; ?> slots added');
<?php
} else if($numslots == -1) {
etc...
Notice the first if condition.. we now check if $numslots is less than $available_slots, rather than greater than zero.

Related

How to For loop for every 50th number start to end point in PHP

I want For loop to get every 50th number whenever we click next or previous it will get 50+ or 50-
Here's my code
<?php
$startpage=1;
$endpage=3;
for($p=$startpage;$p<=$endpage;$p++)
{
echo file_get_html("mysite.com/mypage.php?offset=$p"); // shows offset=1, offset=2, offset=3
}
//But I want to get offset for 50+ or 50- when click next or previous button
$startpage=0;
$endpage=200;
for($p=$startpage;$p<=$endpage;$p++)
{
echo file_get_html("mysite.com/mypage.php?offset=$p"); // it will work like offset=0, offset=50, offset=100, offset=150, offset=200
}
?>
use $p+=50 instead of $p++
for($p=$startpage;$p<=$endpage;$p+=50)
{
echo file_get_html("mysite.com/mypage.php?offset=$p"); // it will work like offset=0, offset=50, offset=100, offset=150, offset=200
}

Change order of elements in query results array

[edited] I need to display posts from database sorted in a kinda specific way.
There is a page which at set time interval query database via ajax to pull 180 latest post. Each post in db has column "source" which can be "instagram" or "twitter". Ajax returns 30 sets (or less) x 6 posts each (less if there is not enough posts). Than with help of js all sets are hidden and only one set (6 posts) is displayed at a time. After few seconds set is hidden and next one is shown. Think of it like a typical slideshow but with posts instead of images on infinite loop.
At the begining it wasn't important what kind of post were in sets. It could be all 6 posts from twitter or instagram or mixed. But as usual when project was scheduled to finish, I was asked to change the way sets are generated. Now client wants to have only 2 types of sets with posts in particular order (described below).
So my question is how change this (simplified example from my ajax file):
DB details for ref.: table POSTS: id / source / user / date etc.
$sql="SELECT * FROM posts ORDER BY id DESC LIMIT 180";
...
$stmt->setFetchMode(PDO::FETCH_OBJ);
$set=1;
while($row = $stmt->fetch()) {
if($set==1){
echo '<!--start set--><div class="set">';
}
if($row->source="twitter"){
echo '<div class="post twitter">';
echo '{all stuff related to this twitter post}';
echo '</div>';
} else if($row->source="instagram") {
echo '<div class="post instagram">';
echo '{all stuff related to this instagram post}';
echo '</div>';
}
if($set==6) {
echo '</div> <!--//END set-->';
$set=0;
}
}
$set++
}
into something what let me generate those 30 sets but with posts distributed among them using this pattern:
<!--First set should has post in order: --
<div class="set>
<div class="post twitter">{stuff}</div> {instagram post} {instagram post}
{instagram post}{instagram post}{twitter post}
</div> <!--//END set-->
<!--Second set order:-->
<div class="set">
{instagram} {instagram} {twitter}
{twitter} {instagram} {instagram}
</div>
etc.
Of course there is no guarantee that there would be enough post to create all 30 sets with those patterns so I need to create as many sets following those two patterns and leftovers put in sets as before simply in order they are pulled from db.
Thats all.
Thanks in advance for any suggestions / ready solutions ;) etc.
You could try something with a split between the two kind of posts using array_filter.
$posts = $stmt->fetchAll();
$twitterPosts = array_filter($posts, function($post){
return $post->source == "twitter";
});
$instagramPosts = array_filter($posts, function($post){
return $post->source == "instagram";
});
$set=1;
while(!empty($twitterPosts) && !empty($instagramPosts))
{
if($set%2 == 1)
{
$instagramPost1 = array_shift($instagramPosts);
$instagramPost2 = array_shift($instagramPosts);
$twitterPost1 = array_shift($twitterPosts);
}
else
{
$instagramPost1 = array_shift($instagramPosts);
$twitterPost1 = array_shift($twitterPosts);
$twitterPost2 = array_shift($twitterPosts);
}
/* display them */
if($set==6) {//your condition
echo '</div> <!--//END set-->';
$set=0;
}
$set++;
}
/* now one of them is empty, you can just display the other one */
if(!empty($twitterPosts))
/* Display all remaining twitter posts */
elseif(!empty($instagramPosts))
/* Display all remaining instagram posts */
Of course you should add validation that there is still something in the array between 2 array_shift.
I hope this helps !
EDIT : sorry I missed the condition for only 3 item per row, adding it now.

PHP counter file and page forwarding

So i'm writing this code so that you either get forwarded to a certain page if you're the first one to hit the link, or you are sent back to the original page after being displayed a message if you're not what beginner mistake am i making?
<?php
$count = file_get_contents('counter.txt');
$count = trim($count);
if ($count="0")
{
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
header("Location: newpage.html");
}
else
{
fclose($fl);
echo "Sorry but the item has already been sold out";
header("Location: oldpage.html");
}
?>
As for the delay, you can accomplish it two different ways. The first is to use PHP header (like you are currently doing), but change it to look like this:
<?php
header("refresh:5;url=oldpage.html");
echo "Sorry but the item has already been sold out";
?>
The other way is to echo out a piece of HTML code, the meta-refresh:
<?php
echo '<meta http-equiv="refresh" content="2;url=oldpage.html">';
echo "Sorry but the item has already been sold out";
?>
In both examples, 5 is the amount of seconds until the refresh. Experiment with each one to see if it will fit your needs.
This might be some sort of syntax that I'm not familiar with, but none of my scripts have ever had the
<? code
I simply use
<?
Also since you did not delay our header tag the user will not see the previously echoed statement above it. It will automatically redirect before the page has time to output fully.

Function Running When Not Called In PHP

Hi I am running the following script, the problem I am having is that the monthly functions are getting called even though it isn't the first Monday of the month ?. What is supposed to happen is every day the every day runs, every Monday the every Monday runs, every month the monthly runs.
By the way, I havnt called these script with cron on those dates as I have to ask the server owner to setup a cron job each time which is a major pain in the rear as he takes ages to do it, so its easier to just have cron hit the script every day and I control the rest with php.
// SETS THE TIMEZONE TO UK TIME
date_default_timezone_set('Europe/London');
// DEFINES WEEKDAY AND DAY OF THE MONTH
$weekday = date('D');
$dayOfMonth = date('d');
// RUNS THE EVERY DAY FUNCTIONS TO MAIL USERS IN THAT GROUP EVERY DAY
gasoildailyemailer();
dervdailyemailer();
kerodailyemailer();
if ($weekday == 'Mon')
{
// RUNS THE WEEKLY FUNCTIONS TO MAIL USERS IN THAT GROUP EVERY WEEK
gasoilweeklyemailer();
dervweeklyemailer();
keroweeklyemailer();
if ($dayOfMonth <=6)
// RUNS THE MONTHLY FUNCTIONS TO MAIL USERS IN THAT GROUP EVERY MONTH
gasoilmonthlyemailer();
dervmonthlyemailer();
keromonthlyemailer();
}
?>
<?php
function gasoildailyemailer() {
echo 'GAS OIL DAILY';
};
function dervdailyemailer() {
echo 'DERV DAILY';
};
function kerodailyemailer() {
echo 'KERO DAILY';
};
?>
<?php
function gasoilweeklyemailer() {
echo 'GAS OIL WEEKLY';
};
function dervweeklyemailer() {
echo 'DERV WEEKLY';
};
function keroweeklyemailer() {
echo 'KERO WEEKLY';
};
?>
<?php
function gasoilmonthlyemailer() {
echo 'GAS OIL MONTHLY';
};
function dervmonthlyemailer() {
echo 'DERV MONTHLY';
};
function keromonthlyemailer() {
echo 'KERO MONTHLY';
};
?>
This is what you get for not always using braces:
if ($dayOfMonth <=6)
gasoilmonthlyemailer(); // THIS IS INSIDE THE IF
dervmonthlyemailer(); // BUT THIS IS OUTSIDE!
keromonthlyemailer(); // THIS ONE TOO!
Fix it by adding braces as you shoud always do (warning: possible religious argument here; this is just my own view):
if ($dayOfMonth <=6) {
gasoilmonthlyemailer();
dervmonthlyemailer();
keromonthlyemailer();
}
As an aside: you would know that only two of the three functions were being incorrectly called. Why not spell that out explicitly so that everyone else benefits from that knowledge up front?
You're missing the brackets after if ($dayOfMonth <=6).

Something is making my page perform an Ajax call multiple times... [read: I've never been more frustrated with something so 'simple' in my life]

NOTE: This is a long question. I've explained all the 'basics' at the top and then there's some further (optional) information for if you need it.
Hi folks
Basically last night this started happening at about 9PM whilst I was trying to restructure my code to make it a bit nicer for the designer to add a few bits to. I tried to fix it until 2AM at which point I gave up. Came back to it this morning, still baffled.
I'll be honest with you, I'm a pretty bad Javascript developer. Since starting this project Javascript has been completely new to me and I've just learn as I went along. So please forgive me if my code structure is really bad (perhaps give a couple of pointers on how to improve it?).
So, to the problem: to reproduce it, visit http://furnace.howcode.com (it's far from complete). This problem is a little confusing but I'd really appreciate the help.
So in the second column you'll see three tabs
The 'Newest' tab is selected by default. Scroll to the bottom, and 3 further results should be dynamically fetched via Ajax.
Now click on the 'Top Rated' tab. You'll see all the results, but ordered by rating
Scroll to the bottom of 'Top Rated'. You'll see SIX results returned.
This is where it goes wrong. Only a further three should be returned (there are 18 entries in total). If you're observant you'll notice two 'blocks' of 3 returned.
The first 'block' is the second page of results from the 'Newest' tab. The second block is what I just want returned.
Did that make any sense? Never mind!
So basically I checked this out in Firebug. What happens is, from a 'Clean' page (first load, nothing done) it calls ONE POST request to http://furnace.howcode.com/code/loadmore .
But every time you load a new one of the tabs, it makes an ADDITIONAL POST request each time where there should normally only be ONE.
So, can you help me? I'd really appreciate it! At this point you could start independent investigation or read on for a little further (optional) information.
Thanks!
Jack
Further Info (may be irrelevant but here for reference):
It's almost like there's some Javascript code or something being left behind that duplicates it each time. I thought it might be this code that I use to detect when the browser is scrolled to the bottom:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
So what I thought was that code was left behind, and so every time you scroll #col2 (which contains different data for each tab) it detected that and added it for #newest as well. So, I made each tab click give #col2 a dynamic class - either .newestcol, .featuredcol, or .topratedcol. And then I changed the var col=$('.newestcol');dynamically so it would only detect it individually for each tab (makin' any sense?!). But hey, that didn't do anything.
Another useful tidbit: here's the PHP for http://furnace.howcode.com/code/loadmore:
$kind = $this->input->post('kind');
if ($kind == 1){ // kind is 1 - newest
$start = $this->input->post('currentpage');
$data['query'] = "SELECT code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.rating AS rating, code.date,
code_tags.*,
tags.*,
users.firstname AS authorname,
users.id AS authorid,
GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup
FROM code, code_tags, tags, users
WHERE users.id = code.author AND code_tags.code_id = code.id AND tags.id = code_tags.tag_id
GROUP BY code_id
ORDER BY date DESC
LIMIT $start, 15 ";
$this->load->view('code/ajaxlist',$data);
} elseif ($kind == 2) { // kind is 2 - featured
So my jQuery code sends a variable 'kind'. If it's 1, it runs the query for Newest, etc. etc.
The PHP code for furnace.howcode.com/code/ajaxlist is:
<?php // Our query base
// SELECT * FROM code ORDER BY date DESC
$query = $this->db->query($query);
foreach($query->result() as $row) {
?>
<script type="text/javascript">
$('#title-<?php echo $row->codeid;?>').click(function() {
var form_data = {
id: <?php echo $row->codeid; ?>
};
$('#col3').fadeOut('slow', function() {
$.ajax({
url: "<?php echo site_url('code/viewajax');?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#col3').html(msg);
$('#col3').fadeIn('fast');
}
});
});
});
</script>
<div class="result">
<div class="resulttext">
<div id="title-<?php echo $row->codeid; ?>" class="title">
<?php echo anchor('#',$row->codetitle); ?>
</div>
<div class="summary">
<?php echo $row->codesummary; ?>
</div>
<!-- Now insert the 5-star rating system -->
<?php include($_SERVER['DOCUMENT_ROOT']."/fivestars/5star.php");?>
<div class="bottom">
<div class="author">
Submitted by <?php echo anchor('auth/profile/'.$row->authorid,''.$row->authorname);?>
</div>
<?php
// Now we need to take the GROUP_CONCATted tags and split them using the magic of PHP into seperate tags
$tagarray = explode(", ", $row->taggroup);
foreach ($tagarray as $tag) {
?>
<div class="tagbutton" href="#">
<span><?php echo $tag; ?></span>
</div>
<?php } ?>
</div>
</div>
</div>
<?php }
echo " ";?>
<script type="text/javascript">
var newpage = <?php echo $this->input->post('currentpage') + 15;?>;
</script>
So that's everything in PHP. The rest you should be able to view with Firebug or by viewing the Source code. I've put all the Tab/clicking/Ajaxloading bits in the tags at the very bottom. There's a comment before it all kicks off.
Thanks so much for your help!
I think you're right to suspect this code block:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
My take on this is that you keep adding additional event handlers (duplicates, essentially) each time you run this code. You need to remove (unbind) the existing event handlers with every tab click so that you can be sure that it's only firing once:
$('#col2').unbind();
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
Or some such thing. See http://api.jquery.com/unbind/
$('.featurecol'); , $('.topratedcol'); and $('.newestcol'); all refer to the same column and division (<div>). As such, whenever you switch pages, you need to unbind the old scroll before rebinding the new scroll handler. (Or else you'll be appending another scroll handler and getting multiple requests sent, like now)
You can do this by adding an unbind as follows:
var col = $('.newestcol');
col.unbind('scroll');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
You need to do this for all of the columns as they load (code/newest, code/toprated and code/featured).
It could also be
$('#col3').fadeOut('slow', function() {
as the ajax loads there... n number of times as it fades out it calls another ajax request.
not saying its the defenet answer but something looking into...

Categories