Ive been building a data driven website displaying general info about countries in the world. Its been made so that 1 country is displayed per page and you can move the next country by clicking a pagination link. Only problem that I am having is I cannot limit the amount of visible links. I did try this for loop with the first line as this: for ($i = $Page; $i <= min($Page + 9, $TotalRecords); $i++) { which does reduce it to the 10 records however this does result in the website breaking when I test the web address by entering index.php?page=aa.
<nav class="mt-5">
<ul class="pagination pagination-lg justify-content-center">
<?php
if( isset($Page) ) {
if ($Page > 1 ) {
?>
<li class="page-item">
«
</li>
<?php
}
}
?>
<?php
global $ConnectingDB;
$sql = "SELECT COUNT(*) FROM countriesinfo";
$stmt = $ConnectingDB->query($sql);
$RowPagination = $stmt->fetch();
$TotalRecords = array_shift($RowPagination);
$RecordPagination = $TotalRecords / 1;
$RecordPagination = ceil($RecordPagination);
for ($i = $Page; $i <= $RecordPagination; $i++) {
if( isset($Page) ) {
if ($i == $Page)
{
?>
<li class="page-item active">
<?php echo $i; ?>
</li>
<?php
} else {
?>
<li class="page-item">
<?php echo $i; ?>
</li>
<?php
}
}
}
?>
<?php if (isset($Page) && !empty($Page) ) {
if ($Page+1 <= $RecordPagination) {
?>
<li class="page-item">
»
</li>
<?php
}
}
?>
</ul>
</nav>
I test the web address by entering index.php?page=aa.
You can check to make sure the get variable is a number by using php is_numeric() bulit in function
and if it isn't force it to number 1.
This will stop the website from breaking when someone manipulate the page varible.
Here is a code to help you out, put at the beginning of the page.
if(is_numeric($page)){
$page = $page; // if $page is a number do nothing
}else{
$page = 1; //else set $page to 1 which will fetch data from beginning
}
Related
Update
Tested my script outside Wordpress and it works. So the problem with this pagination is inside Wordpress. I did some research and I added this rewrite code to my functions file, but still it doesn't work
function my_rewrite_globe_pagination()
{
add_rewrite_rule('^newspaper/page/([0-9]{1,})/?', 'index.php?paged=$matches[1]', 'top');
}
add_action('init', 'my_rewrite_globe_pagination');
The next button url looks like this: domain/page-name/?page=2
URL in browser after clicking next: domain/page-name/page/2/
Before update
first of all I would like to say I read all the similar questions on stackoverflow but I din't find the solution fitting to my case.
What I'm trying to achieve is a globe numeric pagination at my wordpress page. In my page template I have the code listed below and I have with this code two problems:
one is that I don't know how to change the prev and next buttons to numeric pagination
second whenever I click on the next button I see the same two images as on first page, despite the fact that my url changes to domain/page-name/2/
if (isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 1;
}
$base_dir = trailingslashit(wp_upload_dir()['basedir']);
$base_url = wp_upload_dir()['baseurl'];
$dir_jpg = '/newspaper/jpg/';
$dir_pdf = '/newspaper/pdf/';
$images = glob($base_dir.$dir_jpg.'*.*');
$limit = 2;
$total =count($images);
$total_pages = ceil($total/$limit);
$offset = ($page-1) * $limit;
$images = array_slice($images, $limit);
foreach($images as $image) {
$url = $base_url.$dir_jpg.basename($image);
$filename = substr(basename($image), 0, -4);
$pdfs = $base_url.$dir_pdf.$filename.".pdf";
printf('<img src="%s" alt="'.$filename.'.pdf"><div class="newspaper-hover"></div>', esc_url($url));
}
?>
<ul class="pagination">
<li class="<?php if($page <= 1){ echo 'disabled'; } ?>">
Prev
</li>
<li class="<?php if($page >= $total_pages){ echo 'disabled'; } ?>">
Next
</li>
</ul>
For the first problem you simply have to print $page - 1 and $page + 1 instead "Prev" and "Next" (and check if the current page is the first or the last):
<ul class="pagination">
<li class="<?php if($page <= 1){ echo 'disabled'; } ?>">
<?php echo ($page <= 1) ? "X" : ($page - 1)?>
</li>
<li class="<?php if($page >= $total_pages){ echo 'disabled'; } ?>">
<?php echo ($page >= $total_pages) ? "X" : ($page + 1)?>
</li>
</ul>
The second problem is caused by your incorrect call to array_slice.
According to the documentation, the second parameter must be the start offset of the array ($offset in your case) and the third the length of the array you want ($limit), so this should fix it:
$images = array_slice($images, $offset, $limit);
Problem: One piece (That we can identify currently) is causing a clients product list to call the database over and over again (3600 times) at points when loading a longer list of products.
Code:
<?php foreach ($cats as $cat) :
if (in_array($cat->getId(), [68, 28, 27, 59, 79, 80, 119])) :
$cat_show = Mage::getModel('catalog/category')->load($cat->getId());
$children = $cat_show->getChildrenCategories($cat->getId());
$url1 = $cat_show->getURL();
$showAnyways = in_array(strtolower($cat_show->getName()), ["hats", "juniors", "accessories"]);
if ($cat_show->getShowSidebar() == 1 || $showAnyways) : ?>
<li class="current<?php if ($cat->getId() == $current_cat) { ?> active <?php } ?>">
<?php echo $cat->getName() ?>
<ul>
<?php if ($cat_show->getID() != 68 && $cat_show->getID() != 59) { ?>
<li class="current<?php if ($cat->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>"><a class="view_all" href="<?php echo $url1 ?>"><?php echo $this->__("View All"); ?></a></li>
<?php } ?>
<?php foreach ($children as $subcat) {
$subcat_show = Mage::getModel('catalog/category')->load($subcat->getId());
if ($subcat_show->getShowSidebar() == 1 || in_array($subcat_show->getID(), [84])) {
$grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId());
if ($grand_children) {
$cats_displayed = 0;
foreach ($grand_children as $grand_child) {
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL();
?>
<li class="current<?php if ($grand_child->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>">
<?php echo $grand_child_show->getName() ?>
</li>
<?php $cats_displayed++;
}
}
}
if ($cats_displayed == 0 || !$grand_children) {
$url = Mage::getModel('catalog/category')->load($subcat->getId())->getURL();
?>
<li class="current<?php if ($subcat->getId() == $current_cat && $j == 0) {
$j++; ?> active<?php } ?>">
<?php echo $subcat->getName() ?>
</li>
<?php }
}
} ?>
</ul>
</li>
<?php endif;?>
<?php endif;?>
<?php endforeach; ?>
Can anyone provide me with some pointers on how to make this FAR more efficient and not make so many DB calls.
Should note, I am not an amazing php developer by trade. Main language is python so I am trying to get some advice on the best way to go about fixing this given my less that great knowledge of php itself.
You should never have a database query call inside a for loop. You need to build a query at the start that will get all the data required before the for loop.
Some instant pointers I can see are:
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$url = Mage::getModel('catalog/category')->load($grand_child_show->getId())->getURL();
This is calling the database twice for no reason, you should be able to do this:
$grand_child_show = Mage::getModel('catalog/category')->load($grand_child->getId());
if ($grand_child_show->getShowSidebar() == 1) {
$grand_child_show->getURL();
You should be able to drop all these 'GetModel' functions if at the start of the script you call something like:
$all_grand_children = Mage::getModel('catalog/category')->getAllCategories();
This would return a hash array which you would be able to access relevant items by doing the following inside the for loop:
$grand_children = $all_grand_children[$subcat->getId()];
This would replace
$grand_children = Mage::getModel('catalog/category')->getCategories($subcat->getId());
You should also do a initial call for all of the grand_child and cat_show objects. If you are skilled at SQL you can call just the relevant information by joining the tables in one SQL query.
I have a sql field wehre values are like
1,2,3,4,5,6
if fetch those values and explode them below
$amenities = 1,2,3,4,5,6
$amenities_check = explode( "," , $amenities );
Then I run a foreach loop
<?php
$i = 1;
foreach($amenities_check as $amenities_conf)
{
if( $amenities_conf != "" && $amenities_conf == 6)
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
if ($i++ == 1) break;
}
?>
Now the problem is that this loop is display the same line 6 times and display the correct class of li when it meets the 6 digit in the data if i apply $i++ it only check the first data in the dataset.
Any help that foreach look for the desired values like 1 2 3 and do the function according to it ..
Thanks
Is this what you are looking for?
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else {
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
}
?>
EDIT:
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
}
?>
<li class="not_amen">Smoking Allowed</li>
or like the guys above said, use in_array().
<?php
if (in_array("6", $amenities_check)) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
?>
<li class="not_amen">Smoking Allowed</li>
From the comments, what you actually want to know is if there is a 6 anywhere in the array, so you don't want to be outputting anything at all in the loop. The simplest approach is to use the fairly self-explanatory in_array function; as simple as this:
if( in_array('6', $amenities_conf) )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
Alternatively, break apart your logic from your display by looping through the database result once and preparing structured data based on it. The below is probably over-kill for this example, but shows a general approach:
// While retrieving data from the DB
$amenity_names = array(
1 => 'pets',
// ...
6 => 'smoking'
);
$included_amenities = array();
$amenities_check = explode( "," , $amenities );
foreach ( $amenities_check as $amenity )
{
$name = $amenity_names[$amenity];
$included_amenities[$name] = true;
}
// In the View / template code
if( $included_amenities[['smoking'] )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
I have a class name that should change based on certain conditions but either my syntax or my logic seems to be incorrect as it doesn't work:
if ( $hometeam && ($homescore > $awayscore) || $awayteam && ($awayscore > $homescore)){
$status= 'win';
}
if ( $hometeam && ($homescore < $awayscore) || $awayteam && ($awayscore < $homescore)) {
$status= 'lose';
}
if ($homescore == $awayscore) {
$status= 'draw';
}
My elements each have a class="<?php echo $status; ?>" and I want them to be styled differently depending on the value of $status. I didn't use else if because I didn't want it to apply the value and stop but it looks like that is what is happening.
Edit: Some clarification:
<ul class="match group">
<li>
<ul class="team1 <?php echo $status; ?>">
<li class="teamname"><h2><?php echo $homename; ?></h2></li>
<li class="teamscore"><?php echo $homescore; ?></li>
</ul>
</li>
<li>
<ul class="team2 <?php echo $status; ?>">
<li class="teamname"><h2><?php echo $awayname?></h2></li>
<li class="teamscore"><?php echo $awayscore?></li>
</ul>
</li>
<li><ul class="matchinfo">
<li><button>Get Report</button></li>
</ul>
</li>
</ul>
By your logic, there are only two possible outcomes for the value of $status: 'lose' or 'draw'.
Why is this? Basic logic says that unless there is a tie, a game will always have a winner. Your if statement lines up with this. Either $homescore > $awayscore or $homescore < $awayscore (or there is a tie). So in the event of a non-tie, one of the sides of your first if will evaluate to true, and therefore the entire condition will be true since || needs only one truthy. So unless there is a tie, $status will be set to 'win'.
Moving on, basic logic will also tell us that a game always has a loser unless there is a tie. Again, your code conforms to this. In the event of a non-tie, one of the score will be less than the other and therefore your second if will evaluate to true like the first did. Now $status = 'lose'.
Now if there is a tie, $status would equal 'draw', but otherwise $status will always be 'lose' because if the game has a winner, it also has a loser and $status is set to 'lose' after it is set to 'win'.
What you need here is a variable for the winner, loser, and for a draw. Like so:
$winner = '';
$loser = '';
$draw = false;
if($homescore > $awayscore) {
$winner = 'home';
$loser = 'away';
} else if($homescore < $awayscore) {
$winner = 'away';
$loser = 'home';
} else if($homescore === $awayscore) {
$draw = true;
}
(Codepad Demo)
This code also makes use of else if, because you don't need to evaluate the other conditions if you've determined who won and lost.
You need to group your conditions better.
if ( ($hometeam && ($homescore > $awayscore)) || ($awayteam && ($awayscore > $homescore)))
{
$status= 'win';
}
else if ( ($hometeam && ($homescore < $awayscore)) || ($awayteam && ($awayscore < $homescore)))
{
$status= 'lose';
}
else
{
$status= 'draw';
}
if ($homescore > $awayscore) {
$homestatus = 'win';
$awaystatus = 'lose';
} else if ($homescore < $awayscore) {
$homestatus = 'lose';
$awaystatus = 'win';
} else {
$homestatus = 'draw';
$awaystatus = 'draw';
}
<ul class="match group">
<li>
<ul class="team1 <?php echo $homestatus; ?>">
<li class="teamname"><h2><?php echo $homename; ?></h2></li>
<li class="teamscore"><?php echo $homescore; ?></li>
</ul>
</li>
<li>
<ul class="team2 <?php echo $awaystatus; ?>">
<li class="teamname"><h2><?php echo $awayname?></h2></li>
<li class="teamscore"><?php echo $awayscore?></li>
</ul>
</li>
<li><ul class="matchinfo">
<li><button>Get Report</button></li>
</ul>
</li>
</ul>
<?php
// Code not directly relevant omitted (including lots of vars)
//Create pagination links
$first = "First";
$prev = "Prev";
$next = "Next";
$last = "Last";
if($current_page>1)
{
$prevPage = $current_page - 1;
$first = "First";
$prev = "Prev";
}
if($current_page<$total_pages)
{
$nextPage = $current_page + 1;
$next = "Next";
$last = "Last";
}
?>
<html>
<title></title>
<body>
<h2>Here are the records for page <?php echo $current_page; ?></h2>
<ul>
<?php echo $slots; ?>
</ul>
Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
<br />
<?php echo "{$first} | {$prev} | {$next} | {$last}"; ?>
</body>
</html>
EDIT/UPDATE:
I just realized I had a file called test.php a while back. I deleted it but I guess it's still in my site somehow... Nevertheless, I changed the word test with works. Now when I click next, it brings me to mydomain.com/works.php?page=2. But it shows a 404 error :/
Can somebody please tell me where I screwed up? Thanks!
The code certainly looks good; are you sure the problem is in the links being generated? Maybe you are being redirected from the "correct" page for some other reason?